← Back to Home

Git Commands Cheatsheet

Git Commands Cheatsheet

Complete reference guide for Git version control system. From basic commands to advanced workflows, this cheatsheet covers everything you need for effective version control.

Quick Navigation

This cheatsheet is organized by common workflows. Use the navigation to jump to specific sections, or read through for a comprehensive overview.

Pro tip: Use Ctrl+F (Cmd+F on Mac) to search for specific commands or concepts.

Basic Commands

Essential Git commands that every developer should know. These form the foundation of your daily Git workflow.

Repository Setup

Initialize a New Repository

# Initialize a new Git repository
git init
# Initialize with initial branch name
git init -b main

Creates a new Git repository in the current directory. The `-b main` option sets the initial branch name to "main".

Clone an Existing Repository

# Clone a repository
git clone https://github.com/user/repo.git
# Clone to specific directory
git clone https://github.com/user/repo.git my-project
# Clone specific branch
git clone -b branch-name https://github.com/user/repo.git

Downloads a complete copy of a repository, including all history and branches.

Staging & Committing

Check Repository Status

# Check status of working directory
git status
# Short status format
git status -s

Shows which files are staged, modified, or untracked. The `-s` flag provides a concise output.

Add Files to Staging Area

# Add specific file
git add filename.txt
# Add all files in current directory
git add .
# Add all files in repository
git add -A
# Add files interactively
git add -i
# Add parts of a file (patch mode)
git add -p filename.txt

Stages changes for the next commit. Use `-p` for selective staging of parts of files.

Commit Changes

# Commit with message
git commit -m "Your commit message"
# Commit all tracked files (skip staging)
git commit -am "Your commit message"
# Amend last commit
git commit --amend
# Amend with new message
git commit --amend -m "New message"

Commit Message Best Practices:

  • • Use present tense ("Add feature" not "Added feature")
  • • Keep first line under 50 characters
  • • Use blank line before detailed description
  • • Include "why" not just "what"

Viewing History

View Commit History

# Basic log
git log
# One line per commit
git log --oneline
# Graph view with branches
git log --graph --oneline --all
# Last n commits
git log -n 5
# Commits by author
git log --author="John Doe"
# Commits since date
git log --since="2023-01-01"

View Changes

# Show unstaged changes
git diff
# Show staged changes
git diff --staged
# Show changes in specific file
git diff filename.txt
# Compare commits
git diff HEAD~1 HEAD
# Compare branches
git diff main feature-branch

Branching & Merging

Git's branching model allows for parallel development and safe experimentation. Master these commands to leverage Git's full power.

Branch Operations

Branch Management

# List all branches
git branch
# List all branches (including remote)
git branch -a
# Create new branch
git branch feature-branch
# Create and switch to new branch
git checkout -b feature-branch
# Switch to existing branch
git checkout main
# Switch to previous branch
git checkout -
# Delete branch
git branch -d feature-branch
# Force delete branch
git branch -D feature-branch

Modern Git Branch Commands

# Create and switch to new branch (Git 2.23+)
git switch -c feature-branch
# Switch to existing branch
git switch main
# Switch to previous branch
git switch -
# Restore file from another branch
git restore --source=main filename.txt

Git 2.23+ introduced `git switch` and `git restore` for clearer semantics than `git checkout`.

Merging & Rebasing

Merging Branches

# Merge branch into current branch
git merge feature-branch
# Merge without fast-forward
git merge --no-ff feature-branch
# Squash merge (combine all commits)
git merge --squash feature-branch
# Abort merge in case of conflicts
git merge --abort

Rebasing

# Rebase current branch onto main
git rebase main
# Interactive rebase (last 3 commits)
git rebase -i HEAD~3
# Continue rebase after resolving conflicts
git rebase --continue
# Abort rebase
git rebase --abort
# Skip current commit during rebase
git rebase --skip

⚠️ Rebase Warning:

Never rebase commits that have been pushed to a shared repository. This rewrites history and can cause problems for other developers.

Remote Operations

Working with remote repositories is essential for collaboration. These commands help you sync your work with remote servers like GitHub, GitLab, or Bitbucket.

Remote Management

Working with Remotes

# List remote repositories
git remote -v
# Add remote repository
git remote add origin https://github.com/user/repo.git
# Change remote URL
git remote set-url origin https://github.com/user/new-repo.git
# Remove remote
git remote remove origin
# Rename remote
git remote rename origin upstream

Fetching & Pulling

# Fetch changes from remote
git fetch
# Fetch from specific remote
git fetch origin
# Pull changes (fetch + merge)
git pull
# Pull with rebase
git pull --rebase
# Pull specific branch
git pull origin main

`fetch` downloads changes without merging. `pull` downloads and automatically merges changes.

Collaboration

Pushing Changes

# Push to remote repository
git push
# Push to specific remote and branch
git push origin main
# Push new branch and set upstream
git push -u origin feature-branch
# Force push (dangerous!)
git push --force
# Safer force push
git push --force-with-lease
# Push all branches
git push --all
# Push tags
git push --tags

Working with Forks

# Add upstream remote (original repository)
git remote add upstream https://github.com/original/repo.git
# Fetch upstream changes
git fetch upstream
# Merge upstream changes
git merge upstream/main
# Sync fork with upstream
git fetch upstream && git checkout main && git merge upstream/main

Advanced Commands

Advanced Git operations for handling complex scenarios, fixing mistakes, and debugging repository issues.

Undoing Changes

Reset & Revert

# Unstage files
git reset HEAD filename.txt
# Soft reset (keep changes in working directory)
git reset --soft HEAD~1
# Mixed reset (default, unstage changes)
git reset HEAD~1
# Hard reset (discard all changes)
git reset --hard HEAD~1
# Revert commit (create new commit that undoes changes)
git revert HEAD
# Revert multiple commits
git revert HEAD~3..HEAD

⚠️ Reset vs Revert:

`reset` rewrites history (dangerous for shared repos). `revert` creates new commits to undo changes (safe for shared repos).

Stashing Changes

# Stash current changes
git stash
# Stash with message
git stash save "Work in progress on feature X"
# List stashes
git stash list
# Apply most recent stash
git stash apply
# Apply specific stash
git stash apply stash@{2}
# Apply and remove from stash list
git stash pop
# Drop specific stash
git stash drop stash@{1}
# Clear all stashes
git stash clear

Debugging & Analysis

Finding Issues

# Find when a bug was introduced
git bisect start
git bisect bad HEAD
git bisect good v1.0
# Show who modified each line of a file
git blame filename.txt
# Search for text in commit messages
git log --grep="bug fix"
# Search for text in code
git log -S "function_name"
# Show commits that touched a file
git log --follow filename.txt

Cleaning Repository

# Remove untracked files (dry run)
git clean -n
# Remove untracked files
git clean -f
# Remove untracked files and directories
git clean -fd
# Remove ignored files too
git clean -fX
# Garbage collection (cleanup)
git gc
# Prune remote tracking branches
git remote prune origin

Configuration

Customize Git to work better for you with these configuration commands. Set up your identity, preferences, and workflow optimizations.

User Configuration

# Set global username
git config --global user.name "Your Name"
# Set global email
git config --global user.email "your.email@example.com"
# Set default editor
git config --global core.editor "code --wait"
# Set default branch name
git config --global init.defaultBranch main
# Enable colored output
git config --global color.ui auto

Useful Settings

# Auto-correct typos
git config --global help.autocorrect 1
# Remember credentials
git config --global credential.helper store
# Set pull strategy
git config --global pull.rebase true
# Enable rerere (reuse recorded resolution)
git config --global rerere.enabled true
# View all configuration
git config --list

Useful Aliases

Create shortcuts for frequently used commands to speed up your workflow. These aliases can save you significant time during daily development.

Essential Aliases

# Short status
git config --global alias.st status
# Checkout
git config --global alias.co checkout
# Branch
git config --global alias.br branch
# Commit
git config --global alias.ci commit
# Last commit
git config --global alias.last 'log -1 HEAD'
# Unstage
git config --global alias.unstage 'reset HEAD --'

Advanced Aliases

# Visual log with graph
git config --global alias.lg "log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
# Show branches with last commit
git config --global alias.branches 'branch -v'
# Show remotes
git config --global alias.remotes 'remote -v'
# Undo last commit
git config --global alias.undo 'reset HEAD~1 --mixed'
# Amend last commit
git config --global alias.amend 'commit -a --amend'

💡 Pro Tips

  • • Use `git lg` instead of `git log` for a beautiful graph view
  • • Create aliases for your most-used command combinations
  • • Use `!` prefix in aliases to run shell commands: `alias.serve '!python -m http.server'`
  • • Edit your global Git config directly with `git config --global --edit`

📚 Keep Learning

This cheatsheet covers the most common Git commands, but there's always more to learn. Practice these commands regularly, and don't be afraid to experiment with Git's powerful features.