Skip to content
Opsfolk
DevOps

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.

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.com

    Set the name and address every commit you make records as its author.

  • git config --global init.defaultBranch main

    Name the first branch of every new repository main.

  • git config --list --show-origin

    List every setting in force, each with the file it comes from.

    Tip: git config --show-origin user.email answers for one key.

  • git config --global core.editor "code --wait"

    Choose the editor Git opens for commit messages and interactive rebases.

  • git init

    Make the current directory a new repository, with an empty .git.

  • git clone https://github.com/example/app.git

    Copy a repository and all of its history into a new directory named app.

  • git clone https://github.com/example/app.git ~/src/app

    Clone into a directory of your choosing.

  • git clone --depth 1 https://github.com/example/app.git

    Clone only the latest commit: fast, for a build or a quick read.

    Tip: git fetch --unshallow brings the rest of the history later.

  • git config --global alias.lg "log --oneline --graph --decorate"

    Add an alias, so git lg runs 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 = true

    A 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 -sb

    Show the branch, how far it is ahead of or behind its upstream, and each changed file on one line.

  • git add app.js

    Stage a file's changes for the next commit.

  • git add -p

    Go through each change hunk by hunk and choose which to stage.

    Tip: s splits a hunk further, e lets you edit it by hand.

  • git add -A

    Stage every change in the repository, new and deleted files included.

  • git restore --staged app.js

    Unstage 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: -a skips new files: they still need git add.

  • git commit --amend --no-edit

    Fold 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=a1b2c3d

    Make a commit marked to be folded into a1b2c3d by git rebase -i --autosquash.

  • git rm --cached .env

    Stop tracking a file but keep it on disk; add it to .gitignore next.

  • git mv old.js new.js

    Rename a tracked file and stage the rename.

  • git diff --check

    Report trailing whitespace and leftover conflict markers before you commit.

Inspect history

What changed, when, and who changed it.

  • git log --oneline --graph --all

    Every branch's history as a graph, one line per commit.

  • git log -n 5 --stat

    The last five commits, with the files each one changed.

  • git log -p -- src/app.js

    Each commit that touched a file, with its diff.

    Tip: --follow keeps 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/login

    The commits on feature/login that main does not have yet.

  • git show a1b2c3d

    One commit's message and diff.

  • git show main:src/app.js

    A file as it is on another branch, without switching to it.

  • git diff

    The changes in the working tree that are not staged.

  • git diff --staged

    The changes staged for the next commit.

  • git diff main...HEAD

    What 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-diff

    Show changes word by word, for prose and long lines.

  • git blame -L 40,60 src/app.js

    Who last changed each line from 40 to 60, and in which commit.

  • git shortlog -sn

    Count commits per author, the busiest first.

  • git reflog

    Every place HEAD has been, newest first: the way back to a commit a reset or rebase left behind.

Branches

Make, move between, rename and remove branches.

  • git branch

    List local branches, the current one starred.

  • git branch -a

    List local and remote-tracking branches.

  • git branch -vv

    Each branch with its last commit and the upstream it tracks, ahead and behind.

  • git switch feature/login

    Move to an existing branch.

    Tip: A name that exists only on origin makes a local branch that tracks it.

  • git switch -c feature/login

    Make a branch at the current commit and move to it.

  • git switch -c hotfix origin/main

    Make 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/signin

    Rename the current branch.

  • git branch -d feature/login

    Delete a branch that has been merged.

    Warning: -D deletes it even when its commits are merged nowhere.

  • git branch --merged main

    Branches whose work is already in main, and so safe to delete.

  • git switch --detach v1.4.0

    Look at a tag or commit without a branch: commits made here belong to none.

  • git branch -u origin/feature/login

    Set the upstream the current branch pulls from and pushes to.

Merge and rebase

Bring one branch's work into another.

  • git merge feature/login

    Bring a branch's commits into the current one, with a merge commit unless it can fast-forward.

  • git merge --no-ff feature/login

    Always make a merge commit, so the branch stays visible in the history.

  • git merge --ff-only origin/main

    Move forward only if no merge is needed, and refuse otherwise.

  • git merge --abort

    Give up a merge that stopped on conflicts and go back to before it.

  • git rebase main

    Replay the current branch's commits on top of main.

  • git rebase -i HEAD~4

    Reorder, 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 main

    Rebase onto main with each --fixup commit already placed under the commit it fixes.

  • git rebase --continue

    Carry on with a rebase once each conflicted file is fixed and staged with git add.

  • git rebase --abort

    Stop a rebase and put the branch back where it was.

  • git rebase --onto main old-base feature/login

    Move the commits of feature/login after old-base onto main.

  • git cherry-pick -x a1b2c3d

    Copy one commit onto the current branch; -x notes where it came from.

  • git checkout --theirs package-lock.json

    In a conflict, take the other side's whole version of a file.

    Warning: During a rebase the sides swap: --ours is the branch you rebase onto.

  • git mergetool

    Open each conflicted file in the configured merge tool.

  • git config --global rerere.enabled true

    Remember how you resolved a conflict and reuse it when the same one comes back.

Remotes

Fetch, pull and push against shared repositories.

  • git remote -v

    List remotes with the addresses they fetch from and push to.

  • git remote add upstream https://github.com/example/app.git

    Add a second remote, such as the project a fork came from.

  • git remote set-url origin git@github.com:example/app.git

    Point a remote at a new address, here from HTTPS to SSH.

  • git fetch --prune

    Download new commits and branches, and drop remote-tracking branches deleted on the remote.

  • git fetch --all

    Fetch from every remote.

  • git pull --rebase

    Fetch, then replay your local commits on top of what arrived, with no merge commit.

  • git push -u origin HEAD

    Push the current branch under its own name and make it the upstream.

  • git push

    Push the current branch to its upstream.

  • git push --force-with-lease

    Push 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/login

    Delete a branch on the remote.

  • git remote show origin

    A remote's branches, which are tracked and which local branches push where.

  • git ls-remote --heads origin

    The 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.js

    Throw away the unstaged changes to a file.

    Warning: Those changes were never committed, so nothing brings them back.

  • git restore --source=HEAD~2 app.js

    Put a file back as it was two commits ago.

  • git reset --soft HEAD~1

    Undo the last commit and keep its changes staged.

  • git reset HEAD~1

    Undo the last commit and keep its changes in the working tree, unstaged.

  • git reset --hard origin/main

    Make the branch, the index and the working tree match the remote's main.

    Warning: Uncommitted changes are lost. Commits are not: git reflog still has them.

  • git revert a1b2c3d

    Make a new commit that undoes a1b2c3d: the safe undo for a pushed commit.

  • git revert -m 1 a1b2c3d

    Undo a merge commit, keeping the side it was merged into.

  • git reset --hard ORIG_HEAD

    Go 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 -nd

    List the untracked files and directories git clean -fd would delete.

  • git clean -fd

    Delete untracked files and directories.

    Warning: Add -x to also delete ignored files, such as .env and node_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 -u

    Stash untracked files as well.

  • git stash push -- src/app.js

    Stash only the changes to some files.

  • git stash list

    List stashes, the newest as stash@{0}.

  • git stash show -p stash@{1}

    The diff a stash holds.

  • git stash pop

    Apply 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-work

    Make a branch where the stash was made, apply it there and drop it: for a stash that no longer applies cleanly.

Tags and releases

Name a commit for a release.

  • git tag -a v1.2.0 -m "Release 1.2.0"

    Make an annotated tag at the current commit, with its author, date and message.

  • git tag -a v1.1.1 a1b2c3d -m "Release 1.1.1"

    Tag an earlier commit.

  • git tag -l "v1.*"

    List tags that match a pattern.

  • git show v1.2.0

    A tag's message and the commit it names.

  • git push origin v1.2.0

    Push one tag: a plain git push sends none.

  • git push --follow-tags

    Push the branch and the annotated tags on its commits.

    Tip: git push --tags sends every local tag, stray ones included.

  • git tag -d v1.2.0
    git push origin --delete v1.2.0

    Delete a tag here, then on the remote.

  • git describe --tags

    Name the current commit by the nearest tag, such as v1.2.0-4-ga1b2c3d.

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.0

    Start a binary search for the commit that broke something, between a good tag and the current commit.

  • git bisect good

    Mark the commit Git checked out as working; git bisect bad marks it broken.

  • git bisect run npm test

    Let a command decide each step: exit 0 is good, any other code up to 127 bad, 125 skip.

  • git bisect reset

    End 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.0

    Search the files as they were at a tag or commit.

  • git worktree add ../app-hotfix hotfix

    Check out another branch in a second directory, sharing this repository.

  • git worktree list

    List the working trees of this repository.

  • git worktree remove ../app-hotfix

    Remove a working tree once you are done with it.

  • git ls-files

    List the files Git tracks.

  • git check-ignore -v dist/app.js

    Say which .gitignore line 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.git

    Clone the whole history but fetch a file's contents only when a checkout needs them.

  • git sparse-checkout set services/api docs

    Check out only some directories of a large repository.

  • git sparse-checkout disable

    Check out every file again.

  • git submodule update --init --recursive

    Fetch and check out every submodule at the commit the repository records.

    Tip: git clone --recurse-submodules does this as it clones.

  • git maintenance start

    Register the repository for background maintenance: prefetch, commit-graph and repacking on a schedule.

  • git gc

    Pack loose objects and prune unreachable ones now.

  • git count-objects -vH

    How 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 install once 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 --detach or checking out a tag are gone once you switch to a branch.

    Fix: Find them with git reflog and keep them with git branch rescued <commit>. Next time, git switch -c <name> before committing.

  • After an amend or a rebase, git push is 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-lease from 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 .gitignore still shows as changed.

    Fix: .gitignore only affects untracked files. Stop tracking it with git rm --cached <file> and commit.

  • Every line of a file shows as changed, with nothing visible different.

    Fix: Line endings. Add a .gitattributes with * text=auto, then git add --renormalize . and commit.

  • A commit went onto main instead of a feature branch.

    Fix: git branch feature/login to keep it, git reset --hard origin/main to move main back, then git switch feature/login.

  • git pull keeps making "Merge branch 'main' of …" commits.

    Fix: Your branch and the remote both moved. Pull with git pull --rebase, or set git 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 on rerere.enabled so 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-histories once, then resolve and commit.

Every cheat sheet