Git cheat sheet
The Git commands you reach for every day, from a first commit to rebasing, undoing a mistake and finding the commit that broke the build, checked on Git 2.54.
134 entries12 sectionsChecked on Git 2.54Reviewed
Names such as main, feature/login, origin and app.js are examples: put your own branch, remote or file there. The sheet uses git switch and git restore, which split the old git checkout into one command for branches and one for files.
Set up
Who you are, a new repository, a copy of an existing one.
git config --global user.name "Ada Lovelace" git config --global user.email ada@example.comSet the name and address every commit you make records as its author.
git config --global init.defaultBranch mainName the first branch of every new repository
main.git config --list --show-originList every setting in force, each with the file it comes from.
Tip:
git config --show-origin user.emailanswers for one key.git config --global core.editor "code --wait"Choose the editor Git opens for commit messages and interactive rebases.
git initMake the current directory a new repository, with an empty
.git.git clone https://github.com/example/app.gitCopy a repository and all of its history into a new directory named
app.git clone https://github.com/example/app.git ~/src/appClone into a directory of your choosing.
git clone --depth 1 https://github.com/example/app.gitClone only the latest commit: fast, for a build or a quick read.
Tip:
git fetch --unshallowbrings the rest of the history later.git config --global alias.lg "log --oneline --graph --decorate"Add an alias, so
git lgruns the longer command.~/.gitconfig
[user] name = Ada Lovelace email = ada@example.com [init] defaultBranch = main [pull] rebase = true [push] autoSetupRemote = true [fetch] prune = true [rerere] enabled = trueA starting global config: pull rebases, a first push sets the upstream, fetch drops deleted remote branches.
Stage and commit
Choose what goes into the next commit, then record it.
git status -sbShow the branch, how far it is ahead of or behind its upstream, and each changed file on one line.
git add app.jsStage a file's changes for the next commit.
git add -pGo through each change hunk by hunk and choose which to stage.
Tip:
ssplits a hunk further,elets you edit it by hand.git add -AStage every change in the repository, new and deleted files included.
git restore --staged app.jsUnstage a file, leaving its changes in the working tree.
git commit -m "Add retry to the upload client"Record the staged changes as a commit with a one-line message.
git commit -am "Fix typo in README"Stage every change to a tracked file and commit it in one step.
Warning:
-askips new files: they still needgit add.git commit --amend --no-editFold the staged changes into the last commit and keep its message.
Warning: It makes a new commit: once the old one is pushed, the next push needs
--force-with-lease.git commit --amend -m "Better message"Replace the last commit's message.
git commit --fixup=a1b2c3dMake a commit marked to be folded into
a1b2c3dbygit rebase -i --autosquash.git rm --cached .envStop tracking a file but keep it on disk; add it to
.gitignorenext.git mv old.js new.jsRename a tracked file and stage the rename.
git diff --checkReport trailing whitespace and leftover conflict markers before you commit.
Inspect history
What changed, when, and who changed it.
git log --oneline --graph --allEvery branch's history as a graph, one line per commit.
git log -n 5 --statThe last five commits, with the files each one changed.
git log -p -- src/app.jsEach commit that touched a file, with its diff.
Tip:
--followkeeps going past a rename of the file.git log -S "retryCount"Find the commits that added or removed a string: when a line appeared or went.
git log --author="Ada" --since="2 weeks ago"One person's commits over a span of time.
git log main..feature/loginThe commits on
feature/loginthatmaindoes not have yet.git show a1b2c3dOne commit's message and diff.
git show main:src/app.jsA file as it is on another branch, without switching to it.
git diffThe changes in the working tree that are not staged.
git diff --stagedThe changes staged for the next commit.
git diff main...HEADWhat this branch changed since it left
main: the diff a pull request shows.Tip: Three dots compare with the merge base; two dots compare the two tips.
git diff --word-diffShow changes word by word, for prose and long lines.
git blame -L 40,60 src/app.jsWho last changed each line from 40 to 60, and in which commit.
git shortlog -snCount commits per author, the busiest first.
git reflogEvery place
HEADhas been, newest first: the way back to a commit a reset or rebase left behind.
Branches
Make, move between, rename and remove branches.
git branchList local branches, the current one starred.
git branch -aList local and remote-tracking branches.
git branch -vvEach branch with its last commit and the upstream it tracks, ahead and behind.
git switch feature/loginMove to an existing branch.
Tip: A name that exists only on
originmakes a local branch that tracks it.git switch -c feature/loginMake a branch at the current commit and move to it.
git switch -c hotfix origin/mainMake a branch from another starting point, here the remote's
main.git switch -Go back to the branch you were on before.
git branch -m feature/signinRename the current branch.
git branch -d feature/loginDelete a branch that has been merged.
Warning:
-Ddeletes it even when its commits are merged nowhere.git branch --merged mainBranches whose work is already in
main, and so safe to delete.git switch --detach v1.4.0Look at a tag or commit without a branch: commits made here belong to none.
git branch -u origin/feature/loginSet the upstream the current branch pulls from and pushes to.
Merge and rebase
Bring one branch's work into another.
git merge feature/loginBring a branch's commits into the current one, with a merge commit unless it can fast-forward.
git merge --no-ff feature/loginAlways make a merge commit, so the branch stays visible in the history.
git merge --ff-only origin/mainMove forward only if no merge is needed, and refuse otherwise.
git merge --abortGive up a merge that stopped on conflicts and go back to before it.
git rebase mainReplay the current branch's commits on top of
main.git rebase -i HEAD~4Reorder, squash, reword or drop the last four commits.
Warning: It rewrites those commits: do it before they are pushed, or on a branch only you use.
git rebase -i --autosquash mainRebase onto
mainwith each--fixupcommit already placed under the commit it fixes.git rebase --continueCarry on with a rebase once each conflicted file is fixed and staged with
git add.git rebase --abortStop a rebase and put the branch back where it was.
git rebase --onto main old-base feature/loginMove the commits of
feature/loginafterold-baseontomain.git cherry-pick -x a1b2c3dCopy one commit onto the current branch;
-xnotes where it came from.git checkout --theirs package-lock.jsonIn a conflict, take the other side's whole version of a file.
Warning: During a rebase the sides swap:
--oursis the branch you rebase onto.git mergetoolOpen each conflicted file in the configured merge tool.
git config --global rerere.enabled trueRemember how you resolved a conflict and reuse it when the same one comes back.
Remotes
Fetch, pull and push against shared repositories.
git remote -vList remotes with the addresses they fetch from and push to.
git remote add upstream https://github.com/example/app.gitAdd a second remote, such as the project a fork came from.
git remote set-url origin git@github.com:example/app.gitPoint a remote at a new address, here from HTTPS to SSH.
git fetch --pruneDownload new commits and branches, and drop remote-tracking branches deleted on the remote.
git fetch --allFetch from every remote.
git pull --rebaseFetch, then replay your local commits on top of what arrived, with no merge commit.
git push -u origin HEADPush the current branch under its own name and make it the upstream.
git pushPush the current branch to its upstream.
git push --force-with-leasePush a rewritten branch, refusing if someone else pushed to it since your last fetch.
Warning: A fetch updates what the lease compares with: fetch then push, and it no longer protects anyone.
git push origin --delete feature/loginDelete a branch on the remote.
git remote show originA remote's branches, which are tracked and which local branches push where.
git ls-remote --heads originThe branches on a remote and their commits, without fetching anything.
Undo
Take back a change, in the working tree, the index or the history.
git restore app.jsThrow away the unstaged changes to a file.
Warning: Those changes were never committed, so nothing brings them back.
git restore --source=HEAD~2 app.jsPut a file back as it was two commits ago.
git reset --soft HEAD~1Undo the last commit and keep its changes staged.
git reset HEAD~1Undo the last commit and keep its changes in the working tree, unstaged.
git reset --hard origin/mainMake the branch, the index and the working tree match the remote's
main.Warning: Uncommitted changes are lost. Commits are not:
git reflogstill has them.git revert a1b2c3dMake a new commit that undoes
a1b2c3d: the safe undo for a pushed commit.git revert -m 1 a1b2c3dUndo a merge commit, keeping the side it was merged into.
git reset --hard ORIG_HEADGo back to where the branch was before the last merge, rebase or reset.
git branch rescued HEAD@{3}Bring back a lost commit as a branch, from its place in
git reflog.git clean -ndList the untracked files and directories
git clean -fdwould delete.git clean -fdDelete untracked files and directories.
Warning: Add
-xto also delete ignored files, such as.envandnode_modules.
Stash
Put unfinished work aside and bring it back.
git stash push -m "half-done retry"Put staged and unstaged changes aside with a name, and leave a clean tree.
git stash -uStash untracked files as well.
git stash push -- src/app.jsStash only the changes to some files.
git stash listList stashes, the newest as
stash@{0}.git stash show -p stash@{1}The diff a stash holds.
git stash popApply the newest stash and drop it, unless it conflicts.
git stash apply stash@{1}Apply a stash and keep it in the list.
git stash drop stash@{1}Delete one stash.
git stash branch retry-workMake a branch where the stash was made, apply it there and drop it: for a stash that no longer applies cleanly.
Find and fix
Track down a bad commit, search the code, work on two branches at once.
git bisect start git bisect bad git bisect good v1.1.0Start a binary search for the commit that broke something, between a good tag and the current commit.
git bisect goodMark the commit Git checked out as working;
git bisect badmarks it broken.git bisect run npm testLet a command decide each step: exit 0 is good, any other code up to 127 bad, 125 skip.
git bisect resetEnd the search and go back to the branch you started on.
git grep -n "retryCount"Search the tracked files for a string, with line numbers.
git grep "retryCount" v1.1.0Search the files as they were at a tag or commit.
git worktree add ../app-hotfix hotfixCheck out another branch in a second directory, sharing this repository.
git worktree listList the working trees of this repository.
git worktree remove ../app-hotfixRemove a working tree once you are done with it.
git ls-filesList the files Git tracks.
git check-ignore -v dist/app.jsSay which
.gitignoreline ignores a file, and in which file.
Large repos and maintenance
Clone less, check out less, keep the repository fast.
git clone --filter=blob:none https://github.com/example/app.gitClone the whole history but fetch a file's contents only when a checkout needs them.
git sparse-checkout set services/api docsCheck out only some directories of a large repository.
git sparse-checkout disableCheck out every file again.
git submodule update --init --recursiveFetch and check out every submodule at the commit the repository records.
Tip:
git clone --recurse-submodulesdoes this as it clones.git maintenance startRegister the repository for background maintenance: prefetch, commit-graph and repacking on a schedule.
git gcPack loose objects and prune unreachable ones now.
git count-objects -vHHow much room the repository's objects take, in human units.
git lfs track "*.psd"Store files that match a pattern with Git LFS, which keeps large binaries out of the history.
Warning: Git LFS is a separate install: run
git lfs installonce first..gitignore
# dependencies and builds node_modules/ dist/ # local secrets .env .env.* !.env.example # editors and systems .DS_Store .idea/A starting
.gitignore: a trailing/matches directories,!takes a file back out of a pattern.
Pitfalls
What goes wrong, and how to get out of it.
Commits made after
switch --detachor checking out a tag are gone once you switch to a branch.Fix: Find them with
git reflogand keep them withgit branch rescued <commit>. Next time,git switch -c <name>before committing.After an amend or a rebase,
git pushis rejected with "non-fast-forward".Fix: The branch was rewritten. Push with
git push --force-with-lease, and only on a branch nobody else builds on.A teammate's commits vanished from the remote after a
git push --force.Fix: Find their last commit in their clone or in the remote's activity log, then push it back. Use
--force-with-leasefrom now on.A password or key was committed and pushed.
Fix: Revoke and rotate the secret first: it is public from the push. Then remove it from history with
git filter-repo, and force-push.A file added to
.gitignorestill shows as changed.Fix:
.gitignoreonly affects untracked files. Stop tracking it withgit rm --cached <file>and commit.Every line of a file shows as changed, with nothing visible different.
Fix: Line endings. Add a
.gitattributeswith* text=auto, thengit add --renormalize .and commit.A commit went onto
maininstead of a feature branch.Fix:
git branch feature/loginto keep it,git reset --hard origin/mainto movemainback, thengit switch feature/login.git pullkeeps making "Merge branch 'main' of …" commits.Fix: Your branch and the remote both moved. Pull with
git pull --rebase, or setgit config --global pull.rebase true.A rebase stops on the same conflict at commit after commit.
Fix:
git rebase --abort, then squash the branch's commits first, or turn onrerere.enabledso one resolution is reused."fatal: refusing to merge unrelated histories" on a first pull into a new repository.
Fix: The remote was made with its own first commit. Pull with
--allow-unrelated-historiesonce, then resolve and commit.