This is my working Git cheat sheet: the commands I reach for most, grouped by task, each with a short note on what it actually does. You’ll find config, branches, cloning and sparse checkout, log, diff, stash, squash, undoing commits (reset vs revert), and fixes for annoyances like repeated credential prompts and detached HEAD.
Hi there! I first organized these notes for my own reference. You can find any single command online, but having the useful ones together, with the gotchas I ran into, saves a lot of searching. I’ve since refreshed them for current Git.
A note on
mainvsmaster: Many repositories now usemainas the default branch. Wherever you seemasterbelow, substitute your repo’s default branch name.
Quick reference
| Task | Command |
|---|---|
| Show current branch | git branch (current branch is marked with *) |
| Switch to a branch | git switch <branch> or git checkout <branch> |
| Create and switch to a branch | git switch -c <new_branch> or git checkout -b <new_branch> |
| Undo last commit, keep changes | git reset HEAD~ |
| Undo a pushed commit safely | git revert <commit> |
| Save work in progress | git stash |
| Restore a deleted/modified file | git restore <path> or git checkout HEAD -- <path> |
| Fix last commit message | git commit --amend |
General settings
Set your editor for commit messages
If you commit without -m "message", Git opens an editor so you can write the message. Set the one you like. In my case, that’s vim:
git config --global core.editor "vim"Set committer name and email
This is a must. To set them globally, for every repository on your machine:
git config --global user.name "your name"git config --global user.email "your_email@email.com"To set them for one repository only, drop --global and run the commands inside that repository’s folder.
Change the author for the next commit only
git commit --author="your name <your_email@email.com>"List all authors and committers in the log
git log --pretty="%an %ae%n%cn %ce" | sort | uniq| Placeholder | Meaning |
|---|---|
%an | author name |
%ae | author email |
%n | new line |
%cn | committer name |
%ce | committer email |
Every commit records both an author, who wrote the change, and a committer, who applied it. They are usually the same person. They differ after things like rebases, cherry-picks or applied patches.
Branches
| Operation | Command |
|---|---|
| Show current branch | git branch |
| List all branches (local + remote) | git branch -a |
| Switch to an existing branch | git switch <branch> / git checkout <branch> |
| Create a branch (don’t switch) | git branch <new_branch> |
| Create and switch | git switch -c <new_branch> / git checkout -b <new_branch> |
| Push a branch and set upstream | git push -u origin <branch> |
| Delete a local branch | git branch -d <branch> |
| Delete a remote branch | git push origin --delete <branch> (older form: git push origin :<branch>) |
Notes:
git branch <branch_name>only creates a pointer. The repository history doesn’t change. You get a new pointer to the current commit. To start committing on it, switch to it first, then use the usualgit addandgit commit.-dis the “safe” delete. Git refuses to delete a branch that has unmerged changes. Use-Donly when you really mean to throw that work away.- About the old
push origin :<branch>syntax. The colon means “push nothing to this remote branch,” which deletes it. You can also delete branches from your Git host’s web interface; see GitHub’s guide on deleting unused branches.
Fast-forward merge
A typical feature-branch flow:
# Start a new featuregit checkout -b new-feature master
# Edit some filesgit add <file>git commit -m "Start a feature"
# Edit some more filesgit add <file>git commit -m "Finish a feature"
# Merge the feature into mastergit checkout master # switch to mastergit merge new-feature # bring in the changes from new-featuregit branch -d new-feature # clean upIf master hasn’t moved since you branched, Git does a fast-forward. It simply moves the master pointer forward to your latest commit, and no merge commit is created. Use git merge --no-ff new-feature if you always want a merge commit.
Git clone
Clone into the current directory
git init .git remote add origin <repository-url>git pull origin masterYou can also clone straight into a folder you’re already in, as long as it’s empty:
git clone <repository-url> .Clone a specific branch only
Use --single-branch so you fetch only that branch’s history:
git clone -b <branch_or_tag> --single-branch <repository-url>Clone only a subdirectory (sparse checkout)
What you’re after is called a sparse checkout.
Newer Git: the sparse-checkout command
git clone --sparse <repository-url>cd <repo>git sparse-checkout set tempOlder method: configure it by hand
-
Create an empty repository with your remote. This fetches all objects but checks nothing out:
Terminal window mkdir <repo>cd <repo>git initgit remote add -f origin <repository-url> -
Turn on sparse checkout:
Terminal window git config core.sparseCheckout true -
List the folders or files you want in
.git/info/sparse-checkout:Terminal window echo "temp" >> .git/info/sparse-checkout -
Update the repo from the remote:
Terminal window git pull origin master
You’ll now have only the temp folder checked out on disk, and no other paths.
Restoring files
Bring back files you deleted or changed locally
If you accidentally delete or mess up a tracked file, restore it from your last commit:
git restore <path># or, on any Git version:git checkout HEAD -- <path>This restores the file from your local last commit (HEAD), not from the remote. If you want the remote’s version, run git fetch first and then git restore --source=origin/<branch> <path>.
Git remote
A remote is a named bookmark to another repository that you push to or pull from. That repository is usually on a server (GitHub, GitLab, your company’s Git host), but it can also be another folder on your own machine.
Git is distributed, so almost everything happens locally. Remotes are how your repository talks to others:
- You push to share your commits.
- You fetch or pull to get other people’s commits.
git remote add origin git@github.com:<user>/<repo>.gitThis creates a remote named origin pointing at that URL. After that, git push origin <branch> works without typing the full URL.
Is the name origin special? No, it’s just a convention. git clone uses it by default, but you can name a remote anything. Useful related commands:
git remote -v # list remotes and their URLsgit remote set-url origin <new-url> # change a remote's URLgit remote remove <name> # remove a remoteGit log
Last commit on a branch, with graph and file names:
git log -1 --graph --name-only feature/your-feature* commit d1f6696... (HEAD -> feature/your-feature, origin/feature/your-feature)| Author: xx.author <xx.author@yourdomain.com>| Date: Wed Jul 26 15:14:48 2017 -0700|| Your comments.|| your-source-code/file.sh| your-source-code/file02.shSame thing, one line per commit:
git log -1 --graph --name-only --pretty=oneline feature/your-feature* d1f6696... (HEAD -> feature/your-feature, origin/feature/your-feature) Your comments.| your-source-code/file.sh| your-source-code/file02.shFollow a file’s history across renames. The --follow option keeps tracing a single file’s history from before it was renamed:
git log --follow ./renamed_path/to/fileGit diff
| What you want to see | Command |
|---|---|
| Changes in a file vs. last commit | git diff HEAD your_file |
Changes vs. where HEAD was before (e.g. just before a pull) | git diff HEAD@{1} your_file |
| Only what the last commit changed | git diff HEAD^ HEAD or git show |
| Word-level diff between two commits | git diff --word-diff SHA1 SHA2 |
| Last commit: just file names and message | git show --name-only |
| Staged changes (what will be committed) | git diff --staged |
Notes:
HEAD@{1}means “the previous position ofHEAD,” taken from the reflog. After a pull, that’s what you had checked out just before pulling.git diff HEAD^, with only one commit given, compares the previous commit against your working tree. The result includes the last commit’s changes plus any uncommitted edits. If you want only the last commit, give both ends (HEAD^ HEAD) or usegit show.
Git stash
| Operation | Command |
|---|---|
| Stash your local changes | git stash |
| Stash with a description | git stash push -m "message" |
| Stash specific files only | git stash push -- <file> |
| List stashes | git stash list |
| Bring changes back and drop the stash | git stash pop |
| Bring changes back and keep the stash | git stash apply |
| Delete a stash | git stash drop |
The difference between pop and apply:
git stash popapplies the topmost stash (by default) and then throws it away.git stash applyapplies the stash and leaves it in the stash list for later reuse. You can delete it afterwards withgit stash drop.- With conflicts: if
git stash pophits a conflict, it does not drop the stash. In that case it behaves exactly likegit stash apply.
Another way to look at it: git stash pop = git stash apply && git stash drop.
Git squash
Why squash, and how does it help?
There’s a good collection of answers on Software Engineering Stack Exchange. The point I agree with most is this: whoever reviews or merges a pull request usually cares about the net effect (“added feature X”). They don’t care about every intermediate step: fixing typos, tweaking a parameter, swapping a list for a hashmap. Squashing gives them one clean commit that says what changed.
Steps (squash everything on your branch into one commit)
-
Set your current branch name:
Terminal window export curr_branch="<your_current_branch>" -
See the commits you’re about to squash:
Terminal window git log --oneline origin/master..$curr_branch -
Move the branch pointer back to where it split from
master. Your changes stay staged:Terminal window git reset --soft $(git merge-base origin/master $curr_branch) -
Commit again, reusing one of your earlier messages as a starting point:
Terminal window git commit -c <hash_of_one_of_your_previous_commits> -
Sanity-check a file:
Terminal window git diff HEAD <your_file> -
Push the rewritten branch:
Terminal window git push --force-with-lease
--force-with-lease is a safer --force: it refuses to overwrite the remote branch if someone else has pushed to it since you last fetched.
Alternative: run git rebase -i origin/master and mark commits as squash (or fixup) in the editor. This lets you squash selectively instead of all-or-nothing.
Undoing commits: reset vs revert
| Situation | Use | Rewrites history? |
|---|---|---|
| Last commit not pushed yet, want to redo it | git reset HEAD~ | Yes (local only) |
| Commit already pushed, others may have pulled it | git revert <commit> | No |
| Commit pushed, you’re the only one on the branch, want it gone | git reset --hard HEAD~1 + git push --force-with-lease | Yes |
| Just fix the last commit’s message or contents | git commit --amend | Yes |
Undo a commit and redo it
git commit -m "Something comments"git reset HEAD~# << edit files as necessary >>git add ...git commit -c ORIG_HEADgit reset HEAD~moves your branch back one commit. Your changes stay in the working tree, unstaged.git commit -c ORIG_HEADreuses the old commit message and opens the editor so you can change it. If you don’t need to edit the message, use-Cinstead.
Revert a commit that’s already pushed (keeps history)
git revert <commit_hash>git pushgit revert does not delete the commit. It creates a new commit that undoes that commit’s changes. The original commit and the revert both stay in the log, so you have a clear trace of the rollback. This is the safe option on shared branches.
Remove a pushed commit entirely (rewrites history)
You just committed to your local branch and immediately pushed. Then you realize: oh no, I don’t need this change.
git reset --hard HEAD~1 # delete the commit locally (and discard its changes)git push origin HEAD --force-with-lease # make the remote matchBe careful:
--hardthrows away the changes in that commit and any uncommitted work.- Force-pushing rewrites the remote branch’s history, which breaks things for anyone who already pulled it. Only do this on a branch nobody else is using.
Revise the last commit message
git commit --amendThis replaces the last commit. If you’d already pushed it, you’ll need to force-push, with the same caveat as above.
Ignore local changes to a tracked file (without touching .gitignore)
.gitignore only affects untracked files. For a file that’s already tracked, but where you want to keep local edits (say, a config file), tell Git to stop checking it. Source: Practical Git.
git update-index --assume-unchanged <file-to-ignore>You can now change that file however you like, and it won’t show up as modified.
When it breaks: if someone changes that file on the remote, git pull will fail with an error. Then do this:
# tell Git to stop ignoring this filegit update-index --no-assume-unchanged <file-to-ignore>
# stash your local changes to the filegit stash push -- <file-to-ignore>
# pull from remotegit pull
# apply your stashed changes and resolve any conflictgit stash pop
# tell Git to ignore the file againgit update-index --assume-unchanged <file-to-ignore>Tip: --assume-unchanged is technically a performance hint. For “keep my local version of this file,” git update-index --skip-worktree <file> is the flag intended for that job. Undo it with --no-skip-worktree.
Pull the latest changes from another branch into your current branch
To bring another branch’s latest commits into the branch you’re on:
git fetch origingit merge origin/<other-branch>Or do both in one step:
git pull origin <other-branch>If you’d rather replay your commits on top of the other branch instead of creating a merge commit:
git fetch origingit rebase origin/<other-branch>Only rebase commits you haven’t shared yet, or be ready to force-push.
My Git command aliases
These go in your shell config (~/.bashrc, ~/.zshrc, etc.):
alias gs="git status "alias ga="git add "alias gb="git branch "alias gba="git branch -a "alias gbd="git branch -d "alias gbr="git branch -r "alias gc="git commit "alias gd="git diff "alias gco="git checkout "alias glg="git log --graph --name-only "Q&A
Why does Git keep asking for my username and password?
Your name and email (user.name, user.email) only label your commits. They have nothing to do with logging in. To stop the prompts, configure a credential helper. Pick one:
# Keep credentials in memory for a while (not written to disk)git config --global credential.helper cache
# Save credentials permanently in a plain-text file (~/.git-credentials)git config --global credential.helper storeThen run git pull or git push once and enter your credentials. Git will remember them.
- Setting both helpers in a row doesn’t combine them; choose the one you want.
storesaves your credentials unencrypted.- A safer choice is your OS keychain helper (for example
osxkeychainon macOS) or Git Credential Manager. - You can also switch the remote to SSH.
I’m seeing “HEAD detached at xxxxxx”. What now?
You checked out a specific commit, tag or remote branch rather than a local branch. Any commits you make in this state don’t belong to a branch.
To keep work you did while detached, create a branch right where you are:
git switch -c <new-branch-name>To just get back to your branch:
git switch masterWarning: git checkout -f master also gets you out, but it discards all uncommitted changes. Commits you made while detached aren’t attached to any branch either. You can still recover them for a while with git reflog, but it’s easy to lose track of them. Be careful with it.
FAQ
What’s the difference between git reset and git revert?
git reset moves your branch pointer back, removing commits from the branch’s history. It’s fine for local, unpushed work. git revert adds a new commit that undoes an earlier one, so history is preserved. Use it for commits that are already pushed to a shared branch.
How do I undo my last commit but keep the changes?
Run git reset HEAD~. The commit is removed, and its changes stay in your working tree so you can edit and commit again. Use git reset --soft HEAD~ if you want the changes to stay staged.
What’s the difference between git stash pop and git stash apply?
Both put your stashed changes back. pop then deletes the stash; apply keeps it in the list. If pop hits a conflict, it keeps the stash, just like apply.
How do I delete a remote branch?
git push origin --delete <branch>. The older equivalent is git push origin :<branch>.
Should I use git checkout or git switch/git restore?
Both work. Newer Git split checkout’s two jobs into two commands: git switch changes branches and git restore restores files. The split makes it harder to accidentally overwrite files when you meant to change branches.
That’s all I have so far. Enjoy!
[keep: comments]