Skip to main content

98 entries · 9 sections

Git Cheat Sheet

The Git commands that come up in real work: staging, branching, rebasing, syncing with a remote, reading history, and — most importantly — undoing things safely. Everything here is a command you would actually type, grouped the way you actually reach for them.

Setup and configuration

SyntaxWhat it does
git config --global user.name "Ada"Set the author name attached to every commit you make on this machine.
git config --global user.email "a@b.com"Set the commit email. It has to match your host account for commits to link to your profile.
git config --global init.defaultBranch mainName the first branch of new repositories main instead of master.
git config --global core.editor "code --wait"Use VS Code for commit messages and interactive rebase.
git config --global pull.rebase trueMake git pull rebase instead of creating a merge commit every time.
git config --global alias.st statusCreate a shortcut, so git st runs git status.
git config --list --show-originPrint every setting Git resolved and which file it came from. The way to debug a surprising config.
git config --global --editOpen the global config file in your editor.

Starting a repository

SyntaxWhat it does
git initTurn the current directory into a Git repository.
git init -b mainInitialise a repository with main as the starting branch.
git clone <url>Copy a remote repository, its history and its branches into a new folder.
git clone <url> <dir>Clone into a directory name of your choosing instead of the repository name.
git clone --depth 1 <url>Shallow clone: fetch only the latest commit. Much faster on large repositories.
git clone -b <branch> <url>Clone and check out a specific branch.
git remote add origin <url>Point an existing local repository at a remote for the first time.
git remote -vList remotes with their fetch and push URLs.
git remote set-url origin <url>Change where a remote points, for example when moving hosts.

Staging and committing

SyntaxWhat it does
git statusWhat changed, what is staged, and which branch you are on.
git status -sThe same in short form: one line per file.
git add <file>Stage one file for the next commit.
git add .Stage everything under the current directory.
git add -AStage all changes in the whole tree, deletions included.
git add -pStep through each change and choose hunk by hunk what to stage.
git commit -m "msg"Commit the staged changes with a message.
git commit -am "msg"Stage every tracked modified file and commit in one step. Does not pick up new files.
git commit --amendRewrite the previous commit — its message, its contents, or both.
git commit --amend --no-editFold staged changes into the last commit and keep its message.
git reset <file>Unstage a file, keeping the edit in your working tree.
git rm --cached <file>Stop tracking a file but leave it on disk. The fix after committing a secret by mistake.

Branching

SyntaxWhat it does
git branchList local branches; the current one is marked.
git branch -aList local and remote-tracking branches.
git branch -vvList branches with their upstream and how far ahead or behind each is.
git branch <name>Create a branch at the current commit without switching to it.
git switch <name>Switch to an existing branch — the modern replacement for checkout.
git switch -c <name>Create a branch and switch to it.
git switch -Jump back to the branch you were on before.
git checkout <name>The older way to switch branches. Still works everywhere.
git branch -d <name>Delete a branch that has already been merged.
git branch -D <name>Force-delete a branch even when it is not merged.
git branch -m <new>Rename the branch you are on.
git push -u origin <name>Push a new branch and set it as the upstream for future pushes.
git push origin --delete <name>Delete a branch on the remote.

Merging and rebasing

SyntaxWhat it does
git merge <branch>Merge another branch into the current one.
git merge --no-ff <branch>Always create a merge commit, even when a fast-forward would do.
git merge --squash <branch>Collapse a branch's commits into staged changes for one new commit.
git merge --abortCancel a merge that hit conflicts and return to the pre-merge state.
git rebase <branch>Replay your commits on top of another branch for a linear history.
git rebase -i HEAD~5Interactively reorder, squash, reword, edit or drop the last five commits.
git rebase --continueResume a rebase after resolving conflicts and staging the fixes.
git rebase --abortGive up on a rebase and restore the branch exactly as it was.
git cherry-pick <commit>Apply one commit from anywhere onto the current branch.
git cherry-pick --abortUndo a cherry-pick that conflicted.
git mergetoolOpen your configured three-way merge tool on the conflicted files.

Syncing with a remote

SyntaxWhat it does
git fetchDownload new commits from the remote without touching your working tree.
git fetch --all --pruneFetch every remote and delete remote-tracking branches that no longer exist.
git pullFetch, then integrate the remote branch into yours.
git pull --rebaseFetch, then replay your local commits on top — no merge commit.
git pushSend your commits to the tracked remote branch.
git push --force-with-leaseForce-push, but refuse if someone else pushed meanwhile. Always prefer this to --force.
git push --tagsPush tags, which a plain push does not send.
git remote show originShow tracking relationships and what is out of date on a remote.
git remote prune originClean up remote-tracking branches for branches deleted on the server.

Inspecting history

SyntaxWhat it does
git log --onelineOne compact line per commit.
git log --oneline --graph --allDraw the commit graph across every branch. The clearest picture of a tangle.
git log -p <file>The full diff of every commit that touched a file.
git log --follow <file>Keep following a file's history across renames.
git log --author="Ada"Filter history by author.
git log --since="2 weeks ago"Filter history by date.
git log -S "functionName"Find the commits that added or removed a string. The best code archaeology tool Git has.
git show <commit>Show one commit's message and diff.
git diffUnstaged changes: working tree against the index.
git diff --stagedStaged changes: index against the last commit.
git diff main..featureEverything that differs between two branches.
git blame <file>Show the commit and author responsible for each line.
git shortlog -snCommit counts per author.

Undoing things

SyntaxWhat it does
git restore <file>Discard uncommitted changes to a file.
git restore --staged <file>Unstage a file but keep the change in your working tree.
git restore --source=HEAD~2 <file>Bring a file back as it was two commits ago.
git reset --soft HEAD~1Undo the last commit and leave its changes staged.
git reset --mixed HEAD~1Undo the last commit and leave its changes unstaged. This is the default.
git reset --hard HEAD~1Undo the last commit and throw its changes away. Destructive — check git status first.
git revert <commit>Create a new commit that undoes an old one. The safe undo on a shared branch.
git reflogEvery position HEAD has held. The way to recover commits after a bad reset or rebase.
git reset --hard <reflog-sha>Jump back to a state you found in the reflog.
git clean -nPreview which untracked files would be deleted.
git clean -fdActually delete untracked files and directories.

Stashing and tagging

SyntaxWhat it does
git stashPark uncommitted changes and return to a clean working tree.
git stash -uStash untracked files as well.
git stash push -m "wip"Stash with a label so you can find it later.
git stash listShow every stash entry.
git stash popReapply the newest stash and remove it from the list.
git stash apply stash@{2}Reapply a specific stash and keep it in the list.
git stash dropDelete one stash entry.
git stash clearDelete every stash entry.
git tagList tags.
git tag -a v1.0.0 -m "msg"Create an annotated release tag that carries a message and a tagger.
git push origin v1.0.0Publish a single tag.
git describe --tagsName the current commit relative to the nearest tag.

Worth knowing

  • git reflog is the undo button behind the undo button. A hard reset, a botched rebase, a deleted branch — the commits are still there for about 90 days, and the reflog is how you find their SHAs.
  • Never use git push --force on a shared branch. Use --force-with-lease instead: it does exactly the same thing but aborts if the remote moved since your last fetch, which is precisely the case where --force destroys a colleague's work.
  • git add -p is the cheapest code review you will ever get. Walking your own diff hunk by hunk before committing catches stray debug logs, commented-out code and accidental file changes better than any linter.

Try a snippet instead of reading about it

Reference is faster when you can run the thing. Paste a snippet into AltF Code, the free in-browser editor — real syntax highlighting for HTML, CSS, JavaScript, Python, SQL, JSON and more, with HTML, CSS and JavaScript running live in the preview. No install and no sign-up.

Open the editor

Git — common questions

What is the difference between git reset and git revert?
git reset moves the branch pointer backwards, rewriting history — fine on a local branch nobody else has, dangerous once you have pushed. git revert leaves history intact and adds a new commit that undoes the old one, which is the correct choice on any shared branch.
When should I rebase instead of merge?
Rebase your own unpushed feature branch onto an updated main to keep history linear and avoid noise merge commits. Merge when the branch is shared, already pushed, or when the merge itself is meaningful history. The rule of thumb: never rebase commits other people have already pulled.
How do I undo the last commit but keep my changes?
Run git reset --soft HEAD~1 to undo the commit and keep the changes staged, or git reset HEAD~1 (mixed, the default) to keep them unstaged. If you only need to fix the message or add a file, git commit --amend is quicker.
How do I recover a branch I deleted by mistake?
Run git reflog to find the last commit that branch pointed at, then git branch <name> <sha> to recreate it there. Deleting a branch only removes the label; the commits survive until Git garbage-collects unreachable objects, which by default is not for weeks.