Cheatsheet: Git
Created: | Updated:
This cheatsheet assumes that you're already familiar with Git concepts and know the usual init
, pull
, add
, commit
, push
flow. It aims to document commands and flags that I tend to use but forget when I haven't used them in a while.
Branching
List branches
git branch
Create branch
git branch <branch>
Switch to branch
git switch <branch>
Create branch then switch to it
git switch --create <branch>
Or shorthand:
git switch -c <branch>
Rename current branch
git switch --move <new-name>
Or shorthand:
git switch -m <new-name>
Delete branch
git branch --delete <branch>
Or shorthand:
git branch -d <branch>
Delete branch WITHOUT pushing it upstream
git branch --delete --force <branch>
Or shorthand:
git branch -D <branch>
Stashing
Stash changes
git stash
Or to add a message to remember the stash by:
git stash --message <message>
Or shorthand:
git stash -m <message>
List stashes
git stash list
Apply stash to current working tree
git stash apply [<index>]
Apply stash to current working tree THEN remove it
git stash pop [<index>]
Remove stash
git stash drop [<index>]
Remove all stashes
git stash clear
Staging
Stage part of a file
git add --patch <file>
Or shorthand:
git add -p <file>
Note: y
means stage this hunk. n
means don't stage this hunk. s
means split this hunk (not always possible). e
means manually edit this hunk to add the specific lines you want to add (done when hunk is too big and s
is not possible).
Committing
Undo latest commit
git reset HEAD~
Or to keep uncommitted changes staged:
git reset --soft HEAD~
Or to discard ALL uncommitted changes:
git reset --hard HEAD~
Note: You can lose a lot of work when using --hard
, so only use it if you're sure you want to nuke your working tree (yes, you can use reflog
, but still).
Change latest commit message
git commit --amend
Note: There should be no staged changes or else those will be added to the latest commit.
Change previous commit messages
git rebase --interactive <hash>~
Or shorthand:
git rebase -i <hash>~
Then, change pick
to reword
or r
on the commits whose message you want to change.
Add changes to latest commit
Stage new changes, then:
git commit --amend
Or to NOT change the commit message:
git commit --amend --no-edit
Change previous commits
git rebase --interactive <hash>~
Or shorthand:
git rebase -i <hash>~
Then, change pick
to edit
or e
on the commits you want to change. Once you're done with your changes, stage and commit them:
git commit --amend
Or to NOT change the commit message:
git commit --amend --no-edit
Then, move on to the next commit to change:
git rebase --continue
Or to discard the changes you've done so far and exit the interactive rebase:
git rebase --abort