git Cheatsheet

I recommend aliasing common commands in your .gitconfig. Here’s mine as an example.

I use foobarA, foobarB, foobarC as placeholder branch names.

Basics

              [W]------------------+     [S]-------------+
[H]-----+      | Working Copy      |      | Staging Area |
 | HEAD |      | Working Tree      | <--> | Index        |
 +------+      | Working Directory |      |              |
               +-------------------+      +--------------+
git status
git log --all --oneline --graph --decorate
git log --all --pretty=fuller --stat --graph --decorate

# diff HEAD and Working Copy
git diff
# diff [W] and [S]
git diff --staged
# Stage entire files [W --> S]
git add -A
git add foobar.txt

# Unstage entire files [S --> W]
git restore --staged foobar.txt

# Revert all unstaged changes + delete all untracked/ignored files
git clean -fdx
# Make a commit
git commit
# Make a commit that replaces the tip of the current branch
git commit --amend
# List all branches (verbose)
git branch -avv

# Checkout an existing local branch `myawesomebranch`.
# It will also guess and create a tracking branch if no local branch exists.
git checkout myawesomebranch

# Create new branch `myawesomebranch`
git branch myawesomebranch
# Download from remote `origin`
git fetch

# `git fetch`, then attempt to fast forward to match remote
git pull

Revision Archaeology

Revision Selection

git show HEAD    # Current commit
git show HEAD^   # First parent of HEAD
git show HEAD^2  # Second parent of HEAD (useful for merges)
git show HEAD~   # First parent of HEAD
git show HEAD~2  # First parent of first parent of HEAD
git show HEAD~3  # First parent of first parent of first parent of HEAD
# NOT reachable by foobarA, but IS reachable by foobarB
git log foobarA..foobarB

# Reachable by one of foobarA or foobarB, but not both
git log foobarA...foobarB
# Reachable by foobarA or foobarB, but not foobarC
git log foobarA foobarB ^foobarC

More Useful Commands

# filter git logs
git log --grep=foobar

Merging/Rebasing

Rebase

Take the current branch, find the commits that aren’t reachable by origin/master, and replay them at origin/master:

git rebase origin/master

Take the bar branch, find the commits that aren’t reachable by origin/master, and replay them at origin/master:

git rebase origin/master bar

Take the bar branch, find the commits that aren’t reachable by foo branch, and replay them at origin/master:

git rebase --onto origin/master foo bar

Squash the last N commits

To squash the last 3 commits:

git rebase -i HEAD~3

In the following screen, leave the top commit as pick, and set all of the remaining as squash.

Cherrypicking/Reverting

Revert a single commit

git revert PUT_YOUR_COMMIT_HASH_HERE

References