Git cheatsheet
- Many commands accept a
-p
flag (e.g.,git add
,git stash
,git restore
) to interactively choose which changes to apply the command to.
Clone repo at single tag
git clone --depth 1 --branch <tag> <url>
Use the stash
git stash push FILE
git stash # pushes all changes to the stash
git stash pop
git stash apply # like pop but leaves entry on the stash
git stash drop
git stash clear
git stash list
Discard unstaged changes
git restore FILE
Unstage changes
git restore --staged FILE
Undo last commit
git reset HEAD~1 # keep the changes in index
git reset HEAD~1 --hard # throw away the changes!
Restore old version of file
git checkout HEAD~20 -- FILE
Search commit logs
git log --grep PATTERN
Show diffs
git diff # unstaged changes
git diff --staged # staged changes
git diff HEAD # unstaged and staged changes
git diff HEAD~20 # changes since commit
git diff HEAD~20 HEAD~10 -- FILE # changes in between commits
Show earlier version of file
git show HEAD~20:my-file.txt
Branches
# Create a new branch and switch to it
git checkout -b my-new-branch
# Switch to an existing branch
git checkout my-existing-branch
# List branches
git branch
# Delete a branch
git branch -d my-branch
Rebasing and merging
# Interactively rebase
git rebase -i HEAD~5
# Rebase current branch onto master
git rebase master
# Merge master into current branch
git merge master
Remotes
# View list of remote repositories
git remote -v
# Push changes to a remote repository
git push
# Pull changes from a remote repository
git pull
# Push tags to the remote
git push --tags
Tags
# List all tags
git tag
# List tags matching a pattern
git tag -l 'v2.*'
# Create an annotated tag
git tag -a NAME -m MESSAGE
# Show an annotated tag
git show NAME
Store credentials
# omit 'cache ...' to store permanently
$ git config --global credential.helper store 'cache --timeout=3600'
Passwords stored in plaintext!