GeekCoding101 make your way to geek

Git Cheat Sheet: Config, Branches, Stash, Reset & Revert

Practical Git commands with notes: config, branches, sparse checkout, diff, stash, squash, reset vs revert and detached HEAD fixes.

13 min read
Git Notes
On this pageQuick reference

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 main vs master: Many repositories now use main as the default branch. Wherever you see master below, substitute your repo’s default branch name.

Quick reference

TaskCommand
Show current branchgit branch (current branch is marked with *)
Switch to a branchgit switch <branch> or git checkout <branch>
Create and switch to a branchgit switch -c <new_branch> or git checkout -b <new_branch>
Undo last commit, keep changesgit reset HEAD~
Undo a pushed commit safelygit revert <commit>
Save work in progressgit stash
Restore a deleted/modified filegit restore <path> or git checkout HEAD -- <path>
Fix last commit messagegit 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:

Terminal window
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:

Terminal window
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

Terminal window
git commit --author="your name <your_email@email.com>"

List all authors and committers in the log

Terminal window
git log --pretty="%an %ae%n%cn %ce" | sort | uniq
PlaceholderMeaning
%anauthor name
%aeauthor email
%nnew line
%cncommitter name
%cecommitter 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

OperationCommand
Show current branchgit branch
List all branches (local + remote)git branch -a
Switch to an existing branchgit switch <branch> / git checkout <branch>
Create a branch (don’t switch)git branch <new_branch>
Create and switchgit switch -c <new_branch> / git checkout -b <new_branch>
Push a branch and set upstreamgit push -u origin <branch>
Delete a local branchgit branch -d <branch>
Delete a remote branchgit 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 usual git add and git commit.
  • -d is the “safe” delete. Git refuses to delete a branch that has unmerged changes. Use -D only 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:

Terminal window
# Start a new feature
git checkout -b new-feature master
# Edit some files
git add <file>
git commit -m "Start a feature"
# Edit some more files
git add <file>
git commit -m "Finish a feature"
# Merge the feature into master
git checkout master # switch to master
git merge new-feature # bring in the changes from new-feature
git branch -d new-feature # clean up

If 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

Terminal window
git init .
git remote add origin <repository-url>
git pull origin master

You can also clone straight into a folder you’re already in, as long as it’s empty:

Terminal window
git clone <repository-url> .

Clone a specific branch only

Use --single-branch so you fetch only that branch’s history:

Terminal window
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

Terminal window
git clone --sparse <repository-url>
cd <repo>
git sparse-checkout set temp

Older method: configure it by hand

  1. Create an empty repository with your remote. This fetches all objects but checks nothing out:

    Terminal window
    mkdir <repo>
    cd <repo>
    git init
    git remote add -f origin <repository-url>
  2. Turn on sparse checkout:

    Terminal window
    git config core.sparseCheckout true
  3. List the folders or files you want in .git/info/sparse-checkout:

    Terminal window
    echo "temp" >> .git/info/sparse-checkout
  4. 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:

Terminal window
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.
Terminal window
git remote add origin git@github.com:<user>/<repo>.git

This 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:

Terminal window
git remote -v # list remotes and their URLs
git remote set-url origin <new-url> # change a remote's URL
git remote remove <name> # remove a remote

Git log

Last commit on a branch, with graph and file names:

Terminal window
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.sh

Same thing, one line per commit:

Terminal window
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.sh

Follow a file’s history across renames. The --follow option keeps tracing a single file’s history from before it was renamed:

Terminal window
git log --follow ./renamed_path/to/file

Git diff

What you want to seeCommand
Changes in a file vs. last commitgit 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 changedgit diff HEAD^ HEAD or git show
Word-level diff between two commitsgit diff --word-diff SHA1 SHA2
Last commit: just file names and messagegit show --name-only
Staged changes (what will be committed)git diff --staged

Notes:

  • HEAD@{1} means “the previous position of HEAD,” 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 use git show.

Git stash

OperationCommand
Stash your local changesgit stash
Stash with a descriptiongit stash push -m "message"
Stash specific files onlygit stash push -- <file>
List stashesgit stash list
Bring changes back and drop the stashgit stash pop
Bring changes back and keep the stashgit stash apply
Delete a stashgit stash drop

The difference between pop and apply:

  • git stash pop applies the topmost stash (by default) and then throws it away.
  • git stash apply applies the stash and leaves it in the stash list for later reuse. You can delete it afterwards with git stash drop.
  • With conflicts: if git stash pop hits a conflict, it does not drop the stash. In that case it behaves exactly like git 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)

  1. Set your current branch name:

    Terminal window
    export curr_branch="<your_current_branch>"
  2. See the commits you’re about to squash:

    Terminal window
    git log --oneline origin/master..$curr_branch
  3. 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)
  4. Commit again, reusing one of your earlier messages as a starting point:

    Terminal window
    git commit -c <hash_of_one_of_your_previous_commits>
  5. Sanity-check a file:

    Terminal window
    git diff HEAD <your_file>
  6. 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

SituationUseRewrites history?
Last commit not pushed yet, want to redo itgit reset HEAD~Yes (local only)
Commit already pushed, others may have pulled itgit revert <commit>No
Commit pushed, you’re the only one on the branch, want it gonegit reset --hard HEAD~1 + git push --force-with-leaseYes
Just fix the last commit’s message or contentsgit commit --amendYes

Undo a commit and redo it

Terminal window
git commit -m "Something comments"
git reset HEAD~
# << edit files as necessary >>
git add ...
git commit -c ORIG_HEAD
  • git reset HEAD~ moves your branch back one commit. Your changes stay in the working tree, unstaged.
  • git commit -c ORIG_HEAD reuses the old commit message and opens the editor so you can change it. If you don’t need to edit the message, use -C instead.

Revert a commit that’s already pushed (keeps history)

Terminal window
git revert <commit_hash>
git push

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

Terminal window
git reset --hard HEAD~1 # delete the commit locally (and discard its changes)
git push origin HEAD --force-with-lease # make the remote match

Be careful:

  • --hard throws 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

Terminal window
git commit --amend

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

Terminal window
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:

Terminal window
# tell Git to stop ignoring this file
git update-index --no-assume-unchanged <file-to-ignore>
# stash your local changes to the file
git stash push -- <file-to-ignore>
# pull from remote
git pull
# apply your stashed changes and resolve any conflict
git stash pop
# tell Git to ignore the file again
git 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:

Terminal window
git fetch origin
git merge origin/<other-branch>

Or do both in one step:

Terminal window
git pull origin <other-branch>

If you’d rather replay your commits on top of the other branch instead of creating a merge commit:

Terminal window
git fetch origin
git 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.):

Terminal window
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:

Terminal window
# 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 store

Then 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.
  • store saves your credentials unencrypted.
  • A safer choice is your OS keychain helper (for example osxkeychain on 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:

Terminal window
git switch -c <new-branch-name>

To just get back to your branch:

Terminal window
git switch master

Warning: 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]

Thanks for reading my blog post! Feel free to check out my other posts or contact me via the social links in the footer.

Keep reading

All posts