Skip to content

Git Cheatsheet

A complete Git cheatsheet from beginner to advanced — configuration, branching, merging, rebasing, stashing, reflog, worktrees, hooks, submodules, workflows, conflict resolution, and recovery techniques.

Git is a distributed version control system used to track code changes, branch, merge, and collaborate. This cheatsheet covers everything from beginner fundamentals to advanced recovery and workflows.


Term Meaning
Repository (Repo) Project + complete history
Working Directory Your actual files
Staging Area (Index) Changes selected for the next commit
Commit Immutable snapshot of changes
Branch Movable pointer to a commit (default: main)
HEAD Current commit / branch you are on
Remote Repository on another machine (GitHub, GitLab, etc.)
Merge Combine histories of two or more branches
Rebase Replay commits on top of another base
Tag Permanent marker for a specific commit (usually releases)

Git works with three main areas:

  1. Working Directory → your files
  2. Staging Area → changes added with git add
  3. Repository (.git) → committed history
Working Directory --git add--> Staging Area --git commit--> Repository

Terminal window
# Ubuntu / Debian
sudo apt update && sudo apt install git
# Fedora / RHEL / CentOS
sudo dnf install git
# Arch Linux
sudo pacman -S git
# macOS (Homebrew)
brew install git
# Windows
winget install Git.Git
# or https://git-scm.com/download/win
# Check version
git --version

Terminal window
git config --global user.name "Your Full Name"
git config --global user.email "you@example.com"
# Default branch name
git config --global init.defaultBranch main
# Default editor
git config --global core.editor "code --wait" # VS Code
# git config --global core.editor "nano"
# git config --global core.editor "vim"
# Line endings (very important)
git config --global core.autocrlf input # Linux / macOS
git config --global core.autocrlf true # Windows
# Pull behavior
git config --global pull.rebase false # merge (default)
# git config --global pull.rebase true # prefer rebase
# Color
git config --global color.ui auto

Terminal window
git config --list --show-origin # all settings + which file they come from
git config user.name
git config --global --edit # open global config in editor

Config file locations:

  • System: /etc/gitconfig
  • Global: ~/.gitconfig
  • Local (repo): .git/config

Terminal window
git config --global alias.st "status -sb"
git config --global alias.co checkout
git config --global alias.sw switch
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.cm "commit -m"
git config --global alias.ca "commit --amend --no-edit"
git config --global alias.unstage "restore --staged"
git config --global alias.last "log -1 HEAD --stat"
git config --global alias.lg "log --oneline --graph --decorate --all"
git config --global alias.lga "log --oneline --graph --decorate --all -20"
git config --global alias.df "diff --stat"
git config --global alias.dfs "diff --staged"
git config --global alias.please "push --force-with-lease"
git config --global alias.undo "reset --soft HEAD~1"
git config --global alias.cleanup "fetch --prune"

Terminal window
# New local repository
git init
git init my-project
cd my-project
# Bare repository (for servers)
git init --bare my-project.git
# Clone
git clone https://github.com/user/repo.git
git clone git@github.com:user/repo.git # SSH
git clone --depth 1 <url> # shallow (latest commit only)
git clone --branch develop --single-branch <url> # specific branch
git clone --recurse-submodules <url> # with submodules

Terminal window
git status
git status -sb # short + branch info
git status --ignored # also show ignored files

Terminal window
git add file.txt # one file
git add file1.txt file2.js # multiple
git add src/ # directory
git add . # everything (new + modified + deleted)
git add -A # same as above (whole repo)
git add -u # only tracked files
git add -p # interactive hunk selection (extremely useful)
git add -i # interactive mode
git add -N file.txt # intent-to-add (no content yet)

Terminal window
git commit -m "Add user authentication"
git commit -am "Fix login bug" # stage tracked files + commit
git commit --amend # edit last commit (message + files)
git commit --amend --no-edit # add files without changing message
git commit --amend --author="New Name <email@example.com>"
git commit --allow-empty -m "Trigger CI" # empty commit
git commit -v # open editor with diff

Good commit message style (Conventional Commits):

feat: add login page
fix: resolve null pointer in auth
docs: update README installation steps
style: format code with prettier
refactor: extract validation logic
test: add unit tests for user service
chore: update dependencies

Keep the first line under 50 characters. Add a body after a blank line when needed.

Terminal window
git diff # unstaged changes
git diff --staged # staged changes
git diff --stat # summary stats
git diff main # current branch vs main
git diff main...feature # from merge-base to feature
git diff HEAD~2 HEAD # between last two commits
git diff --name-only # file names only
git diff --name-status # names + status (A/M/D)
git difftool # external diff tool

Terminal window
# Basic log
git log
git log --oneline
git log --oneline -10
git log --graph --oneline --decorate --all
# Filtering
git log --author="Rahim"
git log --since="2025-01-01" --until="2025-06-30"
git log --grep="bugfix|hotfix" -i
git log -S "functionName" # pickaxe (code added/removed)
git log -G "regexPattern" # regex search
git log --follow -- file.txt # follow file renames
git log --merge # during a conflict
# Formatting
git log --pretty=format:"%h %an %ar - %s"
git log --pretty=format:"%C(yellow)%h%Creset %C(blue)%an%Creset %s"
# Single commit
git show <commit>
git show HEAD
git show HEAD:path/to/file # file content at that commit
git show --stat <commit>

Terminal window
git branch # list local
git branch -a # all (including remote)
git branch -v # with last commit
git branch -vv # with tracking info
git branch --merged # already merged
git branch --no-merged # not yet merged
git branch feature/payment # create only
git switch feature/payment # switch
git switch -c feature/payment # create + switch (modern)
git checkout -b feature/payment # old syntax
git branch -d feature/payment # safe delete (if merged)
git branch -D feature/payment # force delete
git branch -m old-name new-name # rename
git branch -m new-name # rename current branch

Terminal window
git branch -u origin/main # set upstream
git switch --track origin/feature # create local tracking branch
git switch -c feature origin/feature # same thing
git branch -vv # see what tracks what

Terminal window
git switch --detach v1.2.0 # check out a tag
git switch --detach abc1234 # check out a commit
# You are no longer on a branch
# Commits can be lost easily
# Safe ways to leave:
git switch -c hotfix-from-v1.2 # create a new branch
# or
git switch main # return to an existing branch

Terminal window
git switch main
git merge feature/payment # merge
git merge --no-ff feature/payment # always create a merge commit
git merge --squash feature/payment # combine all commits into staging
git merge --abort # abort on conflict
git merge -m "Merge feature/payment" # custom merge message

Fast-forward vs Merge commit:

  • Fast-forward: target branch pointer simply moves forward
  • --no-ff: forces a merge commit (keeps feature history visible)

Terminal window
git switch feature
git rebase main # replay feature commits on top of main
git rebase --continue # after resolving conflicts
git rebase --abort # cancel entire rebase
git rebase --skip # skip current commit

Terminal window
git rebase -i HEAD~5 # last 5 commits
git rebase -i main # everything after main

Options you will see in the editor:

Command Action
pick keep the commit
reword change the message
edit stop to edit the commit
squash combine with previous and edit message
fix combine with previous and discard message
drop remove the commit
break pause here (for debugging)

Warning: Never rebase a branch that has already been pushed and shared with others. It rewrites history.

Aspect Merge Rebase
History Non-linear (merge commits) Linear (clean)
Shared branches Completely safe Dangerous
Conflicts Resolve once May resolve per commit
Best use Bringing features into main Keeping feature branches up to date
CI / Review Merge commits visible Clean history

Terminal window
git restore --staged file.txt
git restore --staged .
git reset HEAD file.txt # old syntax

Terminal window
git restore file.txt # one file
git restore . # everything
git restore --source=HEAD~1 file.txt # restore from older commit
git checkout -- file.txt # old syntax

Terminal window
git clean -n # dry-run (shows what would be deleted)
git clean -fd # delete files + directories
git clean -fdx # also remove ignored files

Terminal window
# ----- Local only (not yet pushed) -----
git reset --soft HEAD~1 # remove commit, keep changes staged
git reset --mixed HEAD~1 # remove commit + unstage (default)
git reset --hard HEAD~1 # discard everything (dangerous)
git reset --hard <commit> # move to a specific commit
# ----- Already pushed (shared branch) -----
git revert HEAD # create new commit that undoes last one
git revert <commit>
git revert HEAD~3..HEAD # revert a range
git revert -m 1 <merge-commit> # revert a merge (keep parent 1)

Terminal window
git reflog # full history of HEAD
git reflog show feature
git reflog --date=iso
# Example: after accidental hard reset
git reset --hard HEAD@{2}
# or
git switch -c recovery-branch HEAD@{4}

Reflog is usually kept for 30–90 days (gc.reflogExpire).


Terminal window
# Create stash
git stash
git stash push -m "WIP: payment form"
git stash push -u -m "including untracked" # include untracked files
git stash push -a # include ignored files
git stash push -- path/to/file # specific files/folders
# List & apply
git stash list
git stash show
git stash show -p stash@{0} # with patch
git stash apply # apply latest (keep stash)
git stash apply stash@{2}
git stash pop # apply + delete
git stash drop stash@{1}
git stash clear # delete all
# Create branch from stash
git stash branch new-feature stash@{0}

Terminal window
# Add / inspect / remove remotes
git remote add origin https://github.com/user/repo.git
git remote add upstream https://github.com/original/repo.git
git remote -v
git remote show origin
git remote rename origin old-origin
git remote remove origin
git remote set-url origin git@github.com:user/repo.git
# Fetch & pull
git fetch origin
git fetch --all
git fetch --prune # clean deleted remote branches
git fetch origin main:tmp # fetch remote branch into local tmp
git pull # fetch + merge
git pull --rebase
git pull --ff-only # only if fast-forward possible
# Push
git push -u origin main # first push + set upstream
git push origin HEAD # current branch
git push origin HEAD:feature/new # push under different name
git push origin --delete old-feature # delete remote branch
git push --tags
git push --force-with-lease # safer force (fails if someone else pushed)
git push --force # dangerous (avoid)

Terminal window
# Create
git tag v1.0.0 # lightweight
git tag -a v1.0.0 -m "Release version 1.0.0" # annotated (recommended)
git tag -a v1.0.0 <commit-hash>
git tag -s v1.0.0 -m "Signed release" # GPG signed
# List & show
git tag
git tag -l "v1.*"
git show v1.0.0
git tag -n # with messages
# Push & delete
git push origin v1.0.0
git push origin --tags
git push origin --delete v1.0.0 # delete remote tag
git tag -d v1.0.0 # delete local tag

Terminal window
# Blame — who changed each line
git blame file.txt
git blame -L 15,30 file.txt
git blame -w file.txt # ignore whitespace
# Bisect — find the commit that introduced a bug
git bisect start
git bisect bad # current version is bad
git bisect good v1.2.0 # known good point
# Git checks out a middle commit
# Test it, then:
git bisect good # or git bisect bad
# When finished
git bisect reset
# Automated bisect
git bisect start HEAD v1.2.0
git bisect run npm test # run a test script automatically

Terminal window
git cherry-pick <commit> # one commit
git cherry-pick <commit1> <commit2> # multiple
git cherry-pick A..B # range (excludes A)
git cherry-pick A^..B # range (includes A)
git cherry-pick -x <commit> # record original commit in message
git cherry-pick --no-commit <commit> # apply changes without committing
git cherry-pick --continue
git cherry-pick --abort

Terminal window
# Add
git submodule add https://github.com/user/lib.git libs/mylib
git submodule add -b main <url> path
# Clone & update
git clone --recurse-submodules <url>
git submodule init
git submodule update
git submodule update --init --recursive
git submodule update --remote # latest from remote
git submodule update --remote --merge
# Status & sync
git submodule status
git submodule sync
# Remove
git submodule deinit -f path
git rm path
rm -rf .git/modules/path

Subtree alternative (often simpler than submodules):

Terminal window
git subtree add --prefix=libs/lib <url> main --squash
git subtree pull --prefix=libs/lib <url> main --squash
git subtree push --prefix=libs/lib <url> main

Terminal window
git worktree add ../hotfix main
git worktree add -b feature/new ../feature-new
git worktree add ../release v1.2.0
git worktree list
git worktree remove ../hotfix
git worktree prune

The cleanest way to work on multiple branches of the same repository at the same time.


Location: .git/hooks/

Common hooks:

Hook When it runs
pre-commit Just before a commit is created
prepare-commit-msg Before the commit message editor opens
commit-msg After the message is written
post-commit After a commit is made
pre-push Before a push
pre-rebase Before a rebase
post-merge After a merge
post-checkout After a checkout
Terminal window
# Make executable
chmod +x .git/hooks/pre-commit
# Example pre-commit
#!/bin/sh
npm run lint || exit 1

For team-wide hook management, the pre-commit framework (https://pre-commit.com) is the most popular choice.


# Dependencies
node_modules/
vendor/
.venv/
__pycache__/
# Build output
dist/
build/
*.o
*.exe
*.dll
*.so
# Editors & OS
.idea/
.vscode/
*.swp
.DS_Store
Thumbs.db
# Environment & secrets
.env
.env.*
*.pem
*.key
secrets/
# Logs & temp
*.log
tmp/
temp/

Stop tracking an already-tracked file:

Terminal window
git rm --cached file.txt
git rm -r --cached node_modules/
git commit -m "Stop tracking node_modules"

* text=auto eol=lf
*.sh text eol=lf
*.bat text eol=crlf
*.png binary
*.jpg binary
*.pdf binary

Terminal window
git lfs install
git lfs track "*.psd"
git lfs track "*.zip"
git add .gitattributes
git add large-file.psd
git commit -m "Add design assets with LFS"

Terminal window
git status # shows which files have conflicts
# Open the file and remove the markers:
<<<<<<< HEAD
code from current branch
=======
code from other branch
>>>>>>> feature/xyz
git add <resolved-file>
git merge --continue # or git rebase --continue
# Abort
git merge --abort
git rebase --abort

Configure a merge tool:

Terminal window
git config --global merge.tool vscode
git config --global mergetool.vscode.cmd "code --wait $MERGED"
git mergetool

  1. Keep main up to date
  2. Create a feature branch
  3. Commit your work
  4. Push and open a Pull Request
  5. Code review → CI passes → merge
  6. Delete the branch
Terminal window
git switch main
git pull
git switch -c feature/awesome
# ... work ...
git push -u origin HEAD
# Create PR on GitHub

  • main → production
  • develop → integration branch
  • feature/* → new features
  • release/* → release preparation
  • hotfix/* → production bug fixes

  • Small, frequent commits directly to main (or very short-lived branches)
  • Feature flags to hide incomplete work
  • Fast integration and fewer conflicts

Terminal window
# 1. Start a new project
mkdir my-app && cd my-app
git init
echo "# My App" > README.md
git add README.md
git commit -m "chore: initial commit"
# 2. Add remote and push
git remote add origin git@github.com:user/my-app.git
git push -u origin main
# 3. Feature development
git switch -c feature/user-auth
# ... write code ...
git add .
git commit -m "feat: add login and register endpoints"
git push -u origin HEAD
# 4. Main has moved → rebase
git fetch origin
git rebase origin/main
# resolve conflicts if any
git push --force-with-lease
# 5. After PR is merged → local cleanup
git switch main
git pull
git branch -d feature/user-auth
git push origin --delete feature/user-auth
# 6. Release tag
git tag -a v1.0.0 -m "Release v1.0.0"
git push origin v1.0.0

Problem Solution
Wrong commit message (not pushed) git commit --amend
Forgot files in last commit git add <file> + git commit --amend --no-edit
Accidental reset --hard git reflog → git reset --hard HEAD@{n}
Committed on the wrong branch git cherry-pick or git reset + move to correct branch
Push rejected (non-fast-forward) git pull --rebase then git push
Remote branch deleted but still local git fetch --prune
Large file committed by mistake git filter-repo or BFG Repo-Cleaner
Password asked every time Configure a credential helper
Complex merge conflict git merge --abort and try again or use a merge tool
Submodule not updating git submodule update --init --recursive

Never use --force on a shared branch unless the whole team agrees. Prefer --force-with-lease.


Terminal window
git sparse-checkout init --cone
git sparse-checkout set src/ docs/

Terminal window
git clone --filter=blob:none <url> # without blobs
git clone --filter=tree:0 <url> # lazy trees too

Terminal window
git config --global user.signingkey <key-id>
git config --global commit.gpgsign true
git config --global tag.gpgsign true
git log --show-signature

Terminal window
git notes add -m "Reviewed by Rahim" <commit>
git notes show <commit>
git log --show-notes

Terminal window
git gc # garbage collect
git gc --aggressive
git fsck # integrity check
git count-objects -vH # repository size
git repack -ad

  1. Make small, focused commits — one logical change per commit.
  2. Use meaningful branch names: feature/, bugfix/, chore/, hotfix/.
  3. Always git pull --rebase (or at least git pull) before pushing.
  4. Set up .gitignore at the very beginning of the project.
  5. Never commit secrets (API keys, passwords, certificates).
  6. Use signed commits and tags on important projects.
  7. Avoid working directly on main/master — use feature branches.
  8. Always merge via Pull Request / Merge Request.
  9. Run git fetch --prune regularly.
  10. Don’t fear the reflog — it is your safety net.

Terminal window
git status -sb
git add -p
git commit -m "feat: something useful"
git switch -c feature/xyz
git rebase main
git switch main
git merge --no-ff feature/xyz
git push -u origin HEAD
git log --oneline --graph -15
git stash push -m "wip"
git reflog
git fetch --prune


This cheatsheet targets modern Git (2.30+). git switch and git restore are the modern, safer replacements for many uses of the old git checkout. Regular practice makes everything feel natural.

Frequently asked questions

What is the difference between git reset and git revert?

reset rewrites history (safe on local branches). revert creates a new commit that undoes previous changes — safe on shared branches.

When should I use merge vs rebase?

Use merge to preserve history and stay safe on shared branches. Use rebase for a linear history on feature branches. Prefer rebase on feature branches and merge on shared ones.

What is a detached HEAD and how do I get out of it?

You are in a detached HEAD when you check out a specific commit or tag instead of a branch. Create a new branch (git switch -c new-branch) or switch back to an existing branch to leave it.

How do I use git stash?

Temporarily save unfinished work with git stash or git stash push -m "message". Later restore it with git stash pop or git stash apply.

How does .gitignore work?

.gitignore tells Git which untracked files and folders to ignore. To stop tracking a file that is already tracked, use git rm --cached.

What is the reflog and why is it useful?

The reflog records every change to HEAD. It is the best safety net for recovering commits after a bad reset, rebase, or deleted branch.

You're offline Check your connection.