Git Cheat Sheet

Getting Started

Start a new repo:

git init

Clone an existing repo:

git clone <url>

Prepare to Commit

Add untracked file or unstaged changes:

git add <file>

Add all untracked files and unstaged changes:

git add .

Choose which parts of a file to stage:

git add -p

Move file:

git mv <old> <new>

Delete file:

git rm <file>

Tell Git to forget about a file without deleting it:

git rm --cached <file>

Unstage one file:

git reset <file>

Unstage everything:

git reset

Check what you added:

git status

Make Commits

Make a commit (and open text editor to write message):

git commit

Make a commit:

git commit -m 'message'

Commit all unstaged changes:

git commit -am 'message'

Diff Staged/Unstaged Changes

Diff all staged and unstaged changes:

git diff HEAD

Diff just staged changes:

git diff --staged

Diff just unstaged changes:

git diff

Diff Commits

Show diff between a commit and its parent:

git show <commit>

Diff two commits:

git diff <commit> <commit>

Diff one file since a commit:

git diff <commit> <file>

Show a summary of a diff:

git diff <commit> --stat git show <commit> --stat

Discard Your Changes

Delete unstaged changes to one file:

git restore <file> OR git checkout <file>

Delete all staged and unstaged changes to one file:

git restore --staged --worktree <file> OR git checkout HEAD <file>

Delete all staged and unstaged changes:

git reset --hard

Delete untracked files:

git clean

'Stash' all staged and unstaged changes:

git stash

Code Archaeology

Look at a branch's history:

git log main git log --graph main git log --oneline

Show every commit that modified a file:

git log <file>

Show every commit that modified a file, including before it was renamed:

git log --follow <file>

Find every commit that added or removed some text:

git log -G banana

Show who last changed each line of a file:

git blame <file>

Restore an Old File

Get the version of a file from another commit:

git checkout <commit> <file> OR git restore <file> --source <commit>

Add a Remote

git remote add <name> <url>

Pull Changes

Fetch changes (but don't change any of your local branches):

git fetch origin main

Fetch changes and then rebase your current branch:

git pull --rebase

Fetch changes and then merge them into your current branch:

git pull origin main OR git pull

Configure Git

Set a config option:

git config user.name 'Your Name'

Set option globally:

git config --global ...

Add an alias:

git config alias.st status

See all possible config options:

man git-config