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:
- Working Directory → your files
- Staging Area → changes added with
git add - Repository (
.git) → committed history
Working Directory --git add--> Staging Area --git commit--> Repository# Ubuntu / Debiansudo apt update && sudo apt install git
# Fedora / RHEL / CentOSsudo dnf install git
# Arch Linuxsudo pacman -S git
# macOS (Homebrew)brew install git
# Windowswinget install Git.Git# or https://git-scm.com/download/win
# Check versiongit --versiongit config --global user.name "Your Full Name"git config --global user.email "you@example.com"
# Default branch namegit config --global init.defaultBranch main
# Default editorgit 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 / macOSgit config --global core.autocrlf true # Windows
# Pull behaviorgit config --global pull.rebase false # merge (default)# git config --global pull.rebase true # prefer rebase
# Colorgit config --global color.ui autogit config --list --show-origin # all settings + which file they come fromgit config user.namegit config --global --edit # open global config in editorConfig file locations:
- System:
/etc/gitconfig - Global:
~/.gitconfig - Local (repo):
.git/config
git config --global alias.st "status -sb"git config --global alias.co checkoutgit config --global alias.sw switchgit config --global alias.br branchgit config --global alias.ci commitgit 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"# New local repositorygit initgit init my-projectcd my-project
# Bare repository (for servers)git init --bare my-project.git
# Clonegit clone https://github.com/user/repo.gitgit clone git@github.com:user/repo.git # SSHgit clone --depth 1 <url> # shallow (latest commit only)git clone --branch develop --single-branch <url> # specific branchgit clone --recurse-submodules <url> # with submodulesgit statusgit status -sb # short + branch infogit status --ignored # also show ignored filesgit add file.txt # one filegit add file1.txt file2.js # multiplegit add src/ # directorygit add . # everything (new + modified + deleted)git add -A # same as above (whole repo)git add -u # only tracked filesgit add -p # interactive hunk selection (extremely useful)git add -i # interactive modegit add -N file.txt # intent-to-add (no content yet)git commit -m "Add user authentication"git commit -am "Fix login bug" # stage tracked files + commitgit commit --amend # edit last commit (message + files)git commit --amend --no-edit # add files without changing messagegit commit --amend --author="New Name <email@example.com>"git commit --allow-empty -m "Trigger CI" # empty commitgit commit -v # open editor with diffGood commit message style (Conventional Commits):
feat: add login pagefix: resolve null pointer in authdocs: update README installation stepsstyle: format code with prettierrefactor: extract validation logictest: add unit tests for user servicechore: update dependenciesKeep the first line under 50 characters. Add a body after a blank line when needed.
git diff # unstaged changesgit diff --staged # staged changesgit diff --stat # summary statsgit diff main # current branch vs maingit diff main...feature # from merge-base to featuregit diff HEAD~2 HEAD # between last two commitsgit diff --name-only # file names onlygit diff --name-status # names + status (A/M/D)git difftool # external diff tool# Basic loggit loggit log --onelinegit log --oneline -10git log --graph --oneline --decorate --all
# Filteringgit log --author="Rahim"git log --since="2025-01-01" --until="2025-06-30"git log --grep="bugfix|hotfix" -igit log -S "functionName" # pickaxe (code added/removed)git log -G "regexPattern" # regex searchgit log --follow -- file.txt # follow file renamesgit log --merge # during a conflict
# Formattinggit log --pretty=format:"%h %an %ar - %s"git log --pretty=format:"%C(yellow)%h%Creset %C(blue)%an%Creset %s"
# Single commitgit show <commit>git show HEADgit show HEAD:path/to/file # file content at that commitgit show --stat <commit>git branch # list localgit branch -a # all (including remote)git branch -v # with last commitgit branch -vv # with tracking infogit branch --merged # already mergedgit branch --no-merged # not yet merged
git branch feature/payment # create onlygit switch feature/payment # switchgit 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 deletegit branch -m old-name new-name # renamegit branch -m new-name # rename current branchgit branch -u origin/main # set upstreamgit switch --track origin/feature # create local tracking branchgit switch -c feature origin/feature # same thinggit branch -vv # see what tracks whatgit switch --detach v1.2.0 # check out a taggit 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# orgit switch main # return to an existing branchgit switch maingit merge feature/payment # mergegit merge --no-ff feature/payment # always create a merge commitgit merge --squash feature/payment # combine all commits into staginggit merge --abort # abort on conflictgit merge -m "Merge feature/payment" # custom merge messageFast-forward vs Merge commit:
- Fast-forward: target branch pointer simply moves forward
--no-ff: forces a merge commit (keeps feature history visible)
git switch featuregit rebase main # replay feature commits on top of maingit rebase --continue # after resolving conflictsgit rebase --abort # cancel entire rebasegit rebase --skip # skip current commitgit rebase -i HEAD~5 # last 5 commitsgit rebase -i main # everything after mainOptions 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 |
git restore --staged file.txtgit restore --staged .git reset HEAD file.txt # old syntaxgit restore file.txt # one filegit restore . # everythinggit restore --source=HEAD~1 file.txt # restore from older commitgit checkout -- file.txt # old syntaxgit clean -n # dry-run (shows what would be deleted)git clean -fd # delete files + directoriesgit clean -fdx # also remove ignored files# ----- Local only (not yet pushed) -----git reset --soft HEAD~1 # remove commit, keep changes stagedgit 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 onegit revert <commit>git revert HEAD~3..HEAD # revert a rangegit revert -m 1 <merge-commit> # revert a merge (keep parent 1)git reflog # full history of HEADgit reflog show featuregit reflog --date=iso
# Example: after accidental hard resetgit reset --hard HEAD@{2}# orgit switch -c recovery-branch HEAD@{4}Reflog is usually kept for 30–90 days (gc.reflogExpire).
# Create stashgit stashgit stash push -m "WIP: payment form"git stash push -u -m "including untracked" # include untracked filesgit stash push -a # include ignored filesgit stash push -- path/to/file # specific files/folders
# List & applygit stash listgit stash showgit stash show -p stash@{0} # with patchgit stash apply # apply latest (keep stash)git stash apply stash@{2}git stash pop # apply + deletegit stash drop stash@{1}git stash clear # delete all
# Create branch from stashgit stash branch new-feature stash@{0}# Add / inspect / remove remotesgit remote add origin https://github.com/user/repo.gitgit remote add upstream https://github.com/original/repo.gitgit remote -vgit remote show origingit remote rename origin old-origingit remote remove origingit remote set-url origin git@github.com:user/repo.git
# Fetch & pullgit fetch origingit fetch --allgit fetch --prune # clean deleted remote branchesgit fetch origin main:tmp # fetch remote branch into local tmp
git pull # fetch + mergegit pull --rebasegit pull --ff-only # only if fast-forward possible
# Pushgit push -u origin main # first push + set upstreamgit push origin HEAD # current branchgit push origin HEAD:feature/new # push under different namegit push origin --delete old-feature # delete remote branchgit push --tagsgit push --force-with-lease # safer force (fails if someone else pushed)git push --force # dangerous (avoid)# Creategit tag v1.0.0 # lightweightgit 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 & showgit taggit tag -l "v1.*"git show v1.0.0git tag -n # with messages
# Push & deletegit push origin v1.0.0git push origin --tagsgit push origin --delete v1.0.0 # delete remote taggit tag -d v1.0.0 # delete local tag# Blame — who changed each linegit blame file.txtgit blame -L 15,30 file.txtgit blame -w file.txt # ignore whitespace
# Bisect — find the commit that introduced a buggit bisect startgit bisect bad # current version is badgit 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 finishedgit bisect reset
# Automated bisectgit bisect start HEAD v1.2.0git bisect run npm test # run a test script automaticallygit cherry-pick <commit> # one commitgit cherry-pick <commit1> <commit2> # multiplegit cherry-pick A..B # range (excludes A)git cherry-pick A^..B # range (includes A)git cherry-pick -x <commit> # record original commit in messagegit cherry-pick --no-commit <commit> # apply changes without committinggit cherry-pick --continuegit cherry-pick --abort# Addgit submodule add https://github.com/user/lib.git libs/mylibgit submodule add -b main <url> path
# Clone & updategit clone --recurse-submodules <url>git submodule initgit submodule updategit submodule update --init --recursivegit submodule update --remote # latest from remotegit submodule update --remote --merge
# Status & syncgit submodule statusgit submodule sync
# Removegit submodule deinit -f pathgit rm pathrm -rf .git/modules/pathSubtree alternative (often simpler than submodules):
git subtree add --prefix=libs/lib <url> main --squashgit subtree pull --prefix=libs/lib <url> main --squashgit subtree push --prefix=libs/lib <url> maingit worktree add ../hotfix maingit worktree add -b feature/new ../feature-newgit worktree add ../release v1.2.0
git worktree listgit worktree remove ../hotfixgit worktree pruneThe 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 |
# Make executablechmod +x .git/hooks/pre-commit
# Example pre-commit#!/bin/shnpm run lint || exit 1For team-wide hook management, the pre-commit framework (https://pre-commit.com) is the most popular choice.
# Dependenciesnode_modules/vendor/.venv/__pycache__/
# Build outputdist/build/*.o*.exe*.dll*.so
# Editors & OS.idea/.vscode/*.swp.DS_StoreThumbs.db
# Environment & secrets.env.env.**.pem*.keysecrets/
# Logs & temp*.logtmp/temp/Stop tracking an already-tracked file:
git rm --cached file.txtgit 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 binarygit lfs installgit lfs track "*.psd"git lfs track "*.zip"git add .gitattributesgit add large-file.psdgit commit -m "Add design assets with LFS"git status # shows which files have conflicts
# Open the file and remove the markers:<<<<<<< HEADcode from current branch=======code from other branch>>>>>>> feature/xyz
git add <resolved-file>git merge --continue # or git rebase --continue
# Abortgit merge --abortgit rebase --abortConfigure a merge tool:
git config --global merge.tool vscodegit config --global mergetool.vscode.cmd "code --wait $MERGED"git mergetool- Keep
mainup to date - Create a feature branch
- Commit your work
- Push and open a Pull Request
- Code review → CI passes → merge
- Delete the branch
git switch maingit pullgit switch -c feature/awesome# ... work ...git push -u origin HEAD# Create PR on GitHubmain→ productiondevelop→ integration branchfeature/*→ new featuresrelease/*→ release preparationhotfix/*→ 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
# 1. Start a new projectmkdir my-app && cd my-appgit initecho "# My App" > README.mdgit add README.mdgit commit -m "chore: initial commit"
# 2. Add remote and pushgit remote add origin git@github.com:user/my-app.gitgit push -u origin main
# 3. Feature developmentgit 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 → rebasegit fetch origingit rebase origin/main# resolve conflicts if anygit push --force-with-lease
# 5. After PR is merged → local cleanupgit switch maingit pullgit branch -d feature/user-authgit push origin --delete feature/user-auth
# 6. Release taggit 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.
git sparse-checkout init --conegit sparse-checkout set src/ docs/git clone --filter=blob:none <url> # without blobsgit clone --filter=tree:0 <url> # lazy trees toogit config --global user.signingkey <key-id>git config --global commit.gpgsign truegit config --global tag.gpgsign truegit log --show-signaturegit notes add -m "Reviewed by Rahim" <commit>git notes show <commit>git log --show-notesgit gc # garbage collectgit gc --aggressivegit fsck # integrity checkgit count-objects -vH # repository sizegit repack -ad- Make small, focused commits — one logical change per commit.
- Use meaningful branch names:
feature/,bugfix/,chore/,hotfix/. - Always
git pull --rebase(or at leastgit pull) before pushing. - Set up
.gitignoreat the very beginning of the project. - Never commit secrets (API keys, passwords, certificates).
- Use signed commits and tags on important projects.
- Avoid working directly on
main/master— use feature branches. - Always merge via Pull Request / Merge Request.
- Run
git fetch --pruneregularly. - Don’t fear the reflog — it is your safety net.
git status -sbgit add -pgit commit -m "feat: something useful"git switch -c feature/xyzgit rebase maingit switch maingit merge --no-ff feature/xyzgit push -u origin HEADgit log --oneline --graph -15git stash push -m "wip"git refloggit fetch --prune- Official free book: Pro Git
- Official documentation: https://git-scm.com/doc
- Interactive learning: https://learngitbranching.js.org
- Visual cheatsheet: https://git-school.github.io/visualizing-git
- GitHub Docs: https://docs.github.com/en/get-started
- Oh Shit, Git!?! (recovery guide): https://ohshitgit.com
- Conventional Commits: https://www.conventionalcommits.org
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.