Git - Command Reference A-G

Reference

Complete reference for Git commands A-G with syntax, options, examples, and practical use cases. This comprehensive guide covers all essential Git commands alphabetically from 'add' to 'grep'.

add - Add Files to Staging Area

# Basic usage
git add file.txt
git add *.js
git add .                    # Add all files
git add -A                   # Add all including deletions

# Interactive staging
git add -i                   # Interactive mode
git add -p                   # Patch mode (selective staging)

# Advanced options
git add -n                   # Dry run (show what would be added)
git add -v                   # Verbose output
git add -f                   # Force add ignored files
git add -u                   # Add only tracked files
# Example output
$ git add -v src/
add 'src/main.js'
add 'src/utils.js'

am - Apply Mailbox Patches

# Apply mailed patches
git am patch.mbox
git am *.patch

# Options
git am --3way               # Use 3-way merge for conflicts
git am --skip               # Skip current patch
git am --continue           # Continue after resolving conflicts
git am --abort              # Abort patch application

# From email
git am < email.txt

annotate - Show Line-by-Line Annotation

# Show who modified each line (alias for blame)
git annotate file.txt

# Options
git annotate -L 10,20 file.txt    # Lines 10-20 only
git annotate -C file.txt          # Detect moves/copies

apply - Apply Patches

# Apply patch file
git apply patch.diff
git apply --check patch.diff      # Check if patch applies cleanly

# Options
git apply --stat patch.diff       # Show patch statistics
git apply --3way patch.diff       # Use 3-way merge
git apply --reverse patch.diff    # Apply patch in reverse
git apply --cached patch.diff     # Apply to index only

archive - Create Archive of Repository

# Create tar archive
git archive HEAD --format=tar > project.tar
git archive --format=tar.gz HEAD > project.tar.gz

# Create zip archive
git archive --format=zip HEAD > project.zip

# Archive specific branch/tag
git archive v1.0 --format=zip > release-v1.0.zip

# Archive with prefix
git archive --prefix=project-1.0/ HEAD > project-1.0.tar

bisect - Binary Search for Bugs

# Start bisecting
git bisect start
git bisect bad              # Current commit is bad
git bisect good v1.0        # v1.0 is known good

# Mark commits during bisect
git bisect good             # Current commit is good
git bisect bad              # Current commit is bad
git bisect skip             # Skip current commit

# Automated bisect
git bisect run test.sh      # Run script to test each commit

# End bisect session
git bisect reset

blame - Show Line History

# Show who modified each line
git blame file.txt

# Options
git blame -L 10,20 file.txt       # Specific line range
git blame -C file.txt             # Detect moved/copied lines
git blame -w file.txt             # Ignore whitespace
git blame --since="1 month ago"   # Limit by date
git blame -e file.txt             # Show email addresses
# Example output
a1b2c3d4 (John Doe 2023-01-15 10:30:25 +0000  1) function calculate() {
e5f6g7h8 (Jane Smith 2023-01-20 14:15:30 +0000  2)   return x + y;
a1b2c3d4 (John Doe 2023-01-15 10:30:25 +0000  3) }

branch - Manage Branches

# List branches
git branch                  # Local branches
git branch -a               # All branches (local + remote)
git branch -r               # Remote branches only
git branch -v               # Verbose (with last commit)

# Create branches
git branch new-feature      # Create branch
git branch new-feature HEAD~2  # Create from specific commit

# Delete branches
git branch -d feature-name  # Safe delete (merged only)
git branch -D feature-name  # Force delete
git branch -dr origin/branch-name  # Delete remote tracking branch

# Rename branches
git branch -m old-name new-name
git branch -M new-name      # Force rename current branch

# Set upstream tracking
git branch -u origin/main
git branch --set-upstream-to=origin/feature

bundle - Create/Extract Repository Bundles

# Create bundle
git bundle create repo.bundle HEAD main
git bundle create backup.bundle --all

# Verify bundle
git bundle verify backup.bundle

# Extract from bundle
git clone backup.bundle new-repo
git fetch backup.bundle main:new-branch

cat-file - Show Git Objects

# Show object content
git cat-file -p HEAD               # Show commit object
git cat-file -p HEAD^{tree}       # Show tree object
git cat-file -p HEAD:file.txt     # Show file content

# Show object type
git cat-file -t HEAD               # commit
git cat-file -t HEAD^{tree}       # tree

# Show object size
git cat-file -s HEAD:file.txt     # File size in bytes

# Batch mode
echo "HEAD" | git cat-file --batch

check-attr - Display Gitattributes Info

# Check attributes for files
git check-attr --all file.txt
git check-attr text *.js
git check-attr eol README.md

# Check multiple attributes
git check-attr text eol merge file.txt
# Example output
file.txt: text: set
file.txt: eol: lf

check-ignore - Debug .gitignore Rules

# Check if files are ignored
git check-ignore file.txt
git check-ignore -v file.txt      # Verbose (show which rule matches)
git check-ignore --no-index file.txt  # Don't use index

# Check multiple files
git check-ignore *.log
find . -name "*.tmp" | git check-ignore --stdin

check-mailmap - Show Canonical Names

# Check mailmap mappings
git check-mailmap "John Doe "
git check-mailmap --stdin < authors.txt

checkout - Switch Branches/Restore Files

# Switch branches
git checkout main
git checkout feature-branch
git checkout -              # Previous branch

# Create and switch to new branch
git checkout -b new-feature
git checkout -b hotfix origin/main

# Checkout specific commit (detached HEAD)
git checkout abc1234
git checkout HEAD~2

# Restore files
git checkout -- file.txt    # Discard changes
git checkout HEAD file.txt  # Restore from HEAD
git checkout main -- file.txt  # Get file from another branch

# Checkout with tracking
git checkout -t origin/feature  # Create tracking branch

cherry-pick - Apply Specific Commits

# Pick single commit
git cherry-pick abc1234

# Pick multiple commits
git cherry-pick abc1234 def5678
git cherry-pick main~4..main~2

# Options
git cherry-pick -n abc1234        # Don't commit automatically
git cherry-pick -x abc1234        # Add source commit reference
git cherry-pick --continue        # Continue after resolving conflicts
git cherry-pick --abort           # Abort cherry-pick operation

# Cherry-pick merge commit
git cherry-pick -m 1 merge-commit

clean - Remove Untracked Files

# Remove untracked files
git clean -f                # Force remove files
git clean -fd               # Remove files and directories
git clean -fx               # Include ignored files

# Interactive clean
git clean -i

# Dry run (show what would be removed)
git clean -n
git clean -nd               # Include directories in dry run

# Exclude files
git clean -f -e "*.log"     # Exclude .log files

clone - Copy Repository

# Basic clone
git clone https://github.com/user/repo.git
git clone [email protected]:user/repo.git

# Clone to specific directory
git clone repo.git my-project

# Clone specific branch
git clone -b develop repo.git

# Shallow clone
git clone --depth 1 repo.git      # Latest commit only
git clone --depth 5 repo.git      # Last 5 commits

# Clone with different remote name
git clone -o upstream repo.git

# Partial clone (Git 2.19+)
git clone --filter=blob:none repo.git  # No file contents
git clone --filter=tree:0 repo.git     # No trees or blobs

# Bare clone
git clone --bare repo.git

commit - Record Changes

# Basic commit
git commit -m "Add new feature"
git commit -am "Fix bug"          # Add and commit tracked files

# Interactive commit
git commit                        # Open editor for message
git commit -v                     # Include diff in editor

# Amend commits
git commit --amend                # Modify last commit
git commit --amend -m "New message"
git commit --amend --no-edit      # Keep same message

# Advanced options
git commit --allow-empty          # Empty commit
git commit --allow-empty-message  # Commit with empty message
git commit -s                     # Add Signed-off-by line
git commit --gpg-sign             # Sign commit with GPG

# Commit specific files
git commit file1.txt file2.txt -m "Update specific files"

commit-tree - Create Commit Object

# Low-level commit creation
git commit-tree tree-sha -m "Initial commit"
git commit-tree tree-sha -p parent-sha -m "Commit message"

# With multiple parents (merge commit)
git commit-tree tree-sha -p parent1 -p parent2 -m "Merge commit"

config - Get/Set Configuration

# View configuration
git config --list              # All settings
git config user.name           # Specific setting
git config --global --list     # Global settings only

# Set configuration
git config user.name "John Doe"
git config user.email "[email protected]"
git config --global user.name "John Doe"

# Unset configuration
git config --unset user.name
git config --global --unset user.name

# Edit configuration file
git config --edit              # Local config
git config --global --edit     # Global config

# Configuration scopes
git config --system            # System-wide
git config --global            # User-specific
git config --local             # Repository-specific

count-objects - Count Repository Objects

# Count loose objects
git count-objects

# Verbose output with pack info
git count-objects -v

# Human-readable sizes
git count-objects -vH
# Example output
$ git count-objects -v
count 152
size 1024
in-pack 1234
packs 2
size-pack 5678
prune-packable 0
garbage 0
size-garbage 0

describe - Describe Commit with Tags

# Describe current commit
git describe
git describe HEAD

# Options
git describe --tags            # Include lightweight tags
git describe --all             # Include branches and tags
git describe --exact-match     # Only exact tag matches
git describe --always          # Show abbreviated commit if no tag

# Describe specific commit
git describe abc1234
git describe --contains abc1234  # Which tag contains this commit
# Example output
v1.2.3-14-g2414721
# v1.2.3: most recent tag
# 14: commits since tag
# g2414721: abbreviated commit hash

diff - Show Differences

# Basic diffs
git diff                       # Working directory vs staging
git diff --staged              # Staging vs last commit
git diff HEAD                  # Working directory vs last commit

# Compare branches/commits
git diff main feature          # Between branches
git diff HEAD~1 HEAD           # Last commit changes
git diff abc1234..def5678      # Commit range

# File-specific diffs
git diff file.txt
git diff main:file.txt feature:file.txt

# Output formats
git diff --stat                # Statistics only
git diff --name-only           # File names only
git diff --word-diff           # Word-level diff
git diff --color-words         # Colored word diff

# Advanced options
git diff --patience            # Patience algorithm
git diff --histogram           # Histogram algorithm
git diff -w                    # Ignore whitespace
git diff --no-index file1 file2  # Compare arbitrary files

diff-tree - Compare Trees

# Compare commit trees
git diff-tree HEAD~1 HEAD
git diff-tree -r HEAD~1 HEAD     # Recursive

# Show files changed
git diff-tree --name-only HEAD~1 HEAD
git diff-tree --name-status HEAD~1 HEAD

fast-export - Export Repository Data

# Export all history
git fast-export --all > export.txt

# Export specific branches
git fast-export main develop > export.txt

# Export with progress
git fast-export --progress=100 --all > export.txt

fast-import - Import Repository Data

# Import from fast-export
git fast-import < export.txt

# Import with statistics
git fast-import --stats < export.txt

fetch - Download from Remote

# Basic fetch
git fetch                      # Default remote (origin)
git fetch origin               # Specific remote
git fetch --all                # All remotes

# Fetch specific branches
git fetch origin main
git fetch origin main:local-main

# Advanced options
git fetch --prune              # Remove stale remote branches
git fetch --depth=1            # Shallow fetch
git fetch --unshallow          # Convert shallow to full

# Fetch tags
git fetch --tags
git fetch origin tag v1.0

fmt-merge-msg - Generate Merge Message

# Generate merge message
git fmt-merge-msg --log < .git/FETCH_HEAD
git fmt-merge-msg --no-log < .git/FETCH_HEAD

for-each-ref - List References

# List all references
git for-each-ref

# List branches only
git for-each-ref refs/heads/

# Custom format
git for-each-ref --format='%(refname:short) %(objectname:short) %(authordate)'

# Sort references
git for-each-ref --sort=-committerdate
git for-each-ref --sort=authorname

# Count references
git for-each-ref --count=5

format-patch - Generate Email Patches

# Generate patches
git format-patch -1 HEAD              # Last commit
git format-patch HEAD~3               # Last 3 commits
git format-patch main..feature        # Range of commits

# Output options
git format-patch -o patches/ HEAD~3   # Output directory
git format-patch --stdout HEAD~1      # To stdout

# Advanced options
git format-patch --cover-letter HEAD~3  # Include cover letter
git format-patch --numbered HEAD~3      # Number patches
git format-patch --thread HEAD~3        # Thread messages

fsck - Verify Repository

# Check repository integrity
git fsck
git fsck --full                # Full check
git fsck --strict              # Stricter checking

# Find dangling objects
git fsck --lost-found

# Check specific objects
git fsck HEAD

gc - Garbage Collection

# Run garbage collection
git gc
git gc --aggressive            # More thorough cleanup
git gc --auto                  # Only if needed

# Prune options
git gc --prune=now             # Prune all unreachable objects
git gc --prune=2.weeks.ago     # Prune objects older than 2 weeks

grep - Search Repository Content

# Basic search
git grep "search term"
git grep -i "case insensitive"   # Case insensitive
git grep -n "function"           # Show line numbers

# Search in specific areas
git grep "TODO" HEAD             # Search in specific commit
git grep "bug" v1.0              # Search in tagged version
git grep "pattern" -- "*.js"    # Search in JS files only

# Advanced patterns
git grep -E "regex pattern"     # Extended regex
git grep -F "literal string"    # Fixed string (no regex)
git grep -w "whole word"         # Whole word matches

# Output options
git grep -l "pattern"            # File names only
git grep -c "pattern"            # Count matches per file
git grep -v "pattern"            # Invert match

# Context
git grep -A 3 -B 3 "pattern"    # 3 lines after and before
git grep -C 5 "pattern"         # 5 lines of context
# Example output
$ git grep -n "function"
src/main.js:15:function calculate() {
src/utils.js:8:function helper() {
tests/test.js:23:function testCase() {

Quick Reference Summary

CommandPurposeCommon Usage
addStage changesgit add .
bisectFind bugsgit bisect start
blameLine historygit blame file.txt
branchManage branchesgit branch -a
checkoutSwitch/restoregit checkout main
cherry-pickApply commitsgit cherry-pick abc1234
cleanRemove untrackedgit clean -fd
cloneCopy repositorygit clone url
commitRecord changesgit commit -m "message"
configConfigurationgit config user.name
diffShow differencesgit diff --staged
fetchDownload changesgit fetch origin
grepSearch contentgit grep "pattern"

This reference covers the essential Git commands from A-G. Each command includes practical examples and common use cases to help you master Git operations efficiently.