Git Cheatsheet - Commit, Branch, Merge, Rebase & Log

Day-to-day Git work clusters into five things: slicing changes into well-formed commits, moving commits between branches, undoing a mistake, confirming that local and remote agree, and finding who introduced a particular line and when. This sheet is organised into staging and committing, branching and merging, undo and revert, remotes and troubleshooting, git log, plus an FAQ and a block of high-frequency supplementary commands. The judgement is never the spelling of a command but whether the operation is reversible. What you touch - the index or the working tree, a local commit or one already pushed - usually leaves exactly one tool available, so the sheet spells out the boundary between restore, which discards working tree changes, reset, which moves the branch pointer and by default leaves the working tree alone, and revert, which adds an inverse commit. Reach for it when a pipeline fails on one commit and you need to locate it, when a rebase has gone wrong and you need to abort, or when you must inspect two versions at once without checking out.

Version Control·44 commands·Last updated 2026-09-10
gitBranchRollbackMerging

Typical Use Case

Daily version control: commit, branch, merge and rebase, revert mistakes, recover deleted branches or staged content, and resolve merge conflicts and remote sync problems.

Commit & Stash 6

git status -s
Quick view of working tree status
git add -p
Interactively stage changes hunk by hunk
git commit -m "msg"
Commit staged changes
git commit --amend
Amend the last commit (message or content)
git stash
Temporarily save changes, useful for switching branches
git stash pop
Restore the most recent stash

Branch & Merge 13

git branch -a
List local and remote branches
git branch -vv
Show local vs remote branch tracking
git switch -c feat/x
Create and switch to a new branch (new syntax)
git merge --no-ff feat/x
Merge branch and preserve merge commit
git rebase main
Rebase current branch onto main for linear history
git rebase -i HEAD~3
Interactive rebase: squash or rewrite last 3 commits
git rebase --abort
Abort the rebase and return to the pre-rebase state
git cherry-pick <sha>
Apply a specific commit to the current branch
git push -u origin feat/x
Push and set upstream, then just git push
git push origin --delete feat/x
Delete a remote branch
git branch -d feat/x
Delete a merged branch
git branch -D feat/x
Force-delete an unmerged branch (use with caution)
git branch --merged
List branches already merged into the current branch

Revert & Undo 5

git restore <file>
Discard working tree changes (new syntax)
git restore --staged <file>
Unstage a file, keep changes
git reset --soft HEAD~1
Undo last commit, keep changes staged
git reset --hard HEAD~1
Discard last commit and changes entirely, use with caution
git revert <sha>
Create a reverse commit to undo changes, safe for shared branches

Remote & Diagnostics 5

git remote -v
View remote repository URLs
git fetch --prune
Fetch and prune deleted remote branch references
git log --oneline --graph
Graphical commit history view
git reflog
View HEAD movement history, lifesaver for recovering lost commits
git blame <file>
Annotate file line by line with last author and commit

Commit History (git log) 10

git log -p
Show the full diff of each commit
git log --stat
Show file change statistics per commit
git log --author="Alice"
Filter commits by author
git log --since="2 weeks ago"
Show commits from the last two weeks
git log --grep="fix"
Filter commits by message keyword
git log -S "function_name"
Find commits that add or remove that string (pickaxe)
git log origin/main..HEAD
Show local commits not yet pushed
git log --follow -- file.js
Follow a file's full history including renames
git log --name-status
Show changed file names and status (A/M/D)
git shortlog -sn
Count commits by author

FAQ 5

Q: How do I undo the last commit?
A: git reset --soft HEAD~1 keeps changes staged; git reset --hard HEAD~1 discards them (use with caution). For pushed commits use git revert <sha>.
Q: What is the difference between git merge and git rebase?
A: merge preserves branch history (creates a merge commit) and suits shared branches; rebase linearizes history (rewrites commits) and suits personal cleanup.
Q: How do I change the last commit message?
A: git commit --amend edits the last commit message or content. If already pushed, use git push --force-with-lease and mind team safety.
Q: How do I stash unfinished changes?
A: git stash saves working tree changes; after switching branches use git stash pop to restore. git stash list shows all stashes.
Q: How do I resolve a merge conflict?
A: Conflicted files are marked with <<<<<<< HEAD and >>>>>>> branch. Edit manually, then git add <file> and git commit to finish.

Parameter matrix

ParameterEffectExample
--amendRewrite the most recent commit, adding a forgotten file or fixing the message.git commit --amend
-pStage by hunk, so you control exactly which parts of a change enter the commit.git add -p
--soft/--mixed/--hardThe three reset modes: keep the index, discard the index, or discard the working tree too.git reset --soft HEAD~1
-iInteractive rebase, where commits can be squashed, reordered or reworded.git rebase -i HEAD~3
--rebaseRebase on pull instead of merging, keeping history linear.git pull --rebase
--no-ffAlways record a merge commit, which keeps the branch point traceable.git merge --no-ff feature
-uLink the pushed branch to its upstream during the push.git push -u origin feature
--force-with-leaseForce push safely by refusing to overwrite commits you have not seen.git push --force-with-lease
--statShow a per-commit summary of which files changed and by how much.git log --stat
--graphDraw the branch topology as an ASCII graph.git log --oneline --graph

Common pitfalls

SymptomAfter git reset --hard, the deleted commits or changes cannot be found.

Cause--hard discards both the index and the working tree in one step, and nothing was recorded before that.

FixFind the lost SHA with git reflog, then restore it with git reset --hard <sha>; before any risky command, run git stash or create a branch.

SymptomThe push is rejected as non-fast-forward.

CauseThe remote holds commits that are not in your local history, usually pushed by someone else.

FixRebase on top of the remote with git pull --rebase, resolve any conflicts, then push again — never reach for a blind --force.

SymptomA force push wiped out commits from a colleague.

Causegit push --force was used directly, which ignores whatever landed on the remote.

FixAlways use git push --force-with-lease; it refuses the push whenever the remote carries commits your local branch has never seen.

SymptomConflict markers such as <<<<<<< are left in the file after a merge.

CauseBoth sides changed the same lines and Git could not merge them automatically.

FixRun git status to list the conflicted files, edit them by hand to remove the markers while keeping the right content, then git add and commit.

SymptomWork stashed with git stash seems to have disappeared.

CauseThe stash was never popped or applied, or the stash list was cleaned up.

FixCheck git stash list and restore with git stash apply stash@{n}; if it was dropped, recover the dangling objects with git fsck --lost-found.

SymptomA commit contains large files or secrets that should never have been tracked.

CauseThey were not excluded in .gitignore, or the ignore rule was added only after the commit.

FixUntrack with git rm --cached and rewrite history using BFG or filter-repo; revoke and rotate any exposed credential immediately.

Troubleshooting

  1. 1Recover a commit you deleted by mistake

    git reflog

    Lists every position HEAD has held, so you can read out the SHA of the lost commit and restore it with reset.

  2. 2See exactly what a given commit changed

    git show <sha>

    Shows the commit metadata together with the full diff introduced by that commit.

  3. 3Find out who changed a line and when

    git blame -L 10,20 file.ts

    Prints the most recent commit and author touching each line, which makes attribution and history tracing easy.

  4. 4Confirm no conflict markers survived a merge

    grep -rn "<<<<<<<" .

    Search the whole tree for markers before committing so that <<<<<<< never reaches the repository.

Command Examples

Recover a commit dropped by reset

git reset --hard HEAD~2\ngit reflog\ngit reset --hard HEAD@{2}

reset --hard 后工作区被清空,但只要没跑 gc,reflog 仍记录每次 HEAD 移动,用 HEAD@{n} 就能找回上一位置。

Output

ba9c3e1 (HEAD) fix: drop temp debug log   <- reflog 里的历史 HEAD\n8f10a42 feat: add pagination\nHEAD@{2}: reset: moving to HEAD~2

Cherry-pick a single commit

git log --oneline -3\ngit cherry-pick 9f2c14b

想只拿另一个分支的某个提交,而不合并整个分支时用 cherry-pick;有冲突时按提示解决后 git cherry-pick --continue。

Common Pitfalls

  • git push origin --delete and git branch -D are irreversible — verify with git branch -a and git log before deleting.
  • Resetting a commit already pushed to a shared branch then force-pushing overwrites teammates' history; use revert on shared commits.
  • git clean -fd (not listed here) deletes untracked files unrecoverably — always preview with git clean -n first.
  • git stash does not include untracked files by default; use git stash -u to include them.

Tips

  • reset --hard discards changes — double-check before running; use git reflog to recover if truly lost.
  • Use revert to undo commits already pushed to shared branches — never reset and force-push or you will break your teammates.
  • switch/restore are newer commands with clearer semantics than checkout; older scripts still use checkout.

FAQ

When should I use git rebase vs git merge?

merge preserves divergent history and creates a merge commit, so it suits shared branches such as merging a feature into main, is easy to roll back as a unit, and never rewrites existing commits. rebase replays your commits onto the target branch to produce a clean linear history, which is great for tidying your own feature branch, but it rewrites commits and should be avoided on branches others share.

Can I undo an already-pushed commit with git reset and then force-push?

Not recommended. reset rewrites history, and force-pushing it can overwrite teammates commits, causing conflicts or lost work. For pushed commits, safely undo with git revert <sha>, which creates a reverse commit. It is fine to use reset --soft/hard only while the commit is still local and unpushed.

I accidentally committed node_modules or .env. How do I remove them?

Run git rm --cached <path> to stop tracking while keeping the file locally, add the rule to .gitignore, then commit once. This only removes the files from version control without deleting them from disk. If a secret was exposed, also rewrite history and rotate the credential.

Can I recover a deleted branch or a commit dropped by reset?

Yes. Unless gc has run, git reflog records every prior position of HEAD and branches; restore with git reset --hard HEAD@{n} or git checkout -b <name> <sha>. If a deleted branch still has its commits, find the sha with git reflog and recreate the branch.

My git stash changes suddenly disappeared?

First check git stash list, and inspect contents with git stash show -p stash@{0}. A pop may leave conflicts that appear as conflict markers you must resolve manually. If it is really gone, use git fsck --lost-found to recover the unreferenced stash commit from the object database. Note git stash does not include untracked files unless you use git stash -u.

Official References

Each command links to its official documentation below, so you can verify the latest usage and read deeper.

Maintained by LaoHand

Publicly updated on Sep 10, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us