Git Command Line Cheat Sheet
Here’s a list of Git commands I use on a regular basis. I also tend to forget many of them regularly so it helps to keep them in one place for easy reference.
If you have oh-my-zsh installed it comes with an assortment of Git aliases that covers many of the commands listed below.
Setup
Add a remote repository:
git remote add origin git@github.com:username/my-repo.git
Push and set up an upstream reference for a branch (first time only):
git push -u origin my-branch
Committing
Interactively stage changes hunk-by-hunk:
git add --patch
Amend the most recent commit:
git commit --amend
Amend the most recent commit without editing the message:
git commit --amend --no-edit
Branching
Create and check out a new branch:
git checkout -b my-branch
Checks out a remote branch:
git fetch && git checkout my-branch
Delete a branch locally:
git branch -d my-branch
Delete a branch remotely:
git push origin :my-branch
List remote branches:
git branch -r
Rename a branch:
git branch -m current-branch-name new-branch-name
Stashing
Save your current changes in a new stash with a message:
git stash save my-stash
List your stashes:
git stash list
Restore a stash at index 0:
git stash apply 0
Delete a stash at index 0:
git stash drop 0
Tags
Create a new tag:
git tag 1.0.0
Push all tags to origin:
git push origin --tags
Delete a tag locally:
git tag -d 1.0.0
Delete a tag remotely:
git push origin :refs/tags/1.0.0
Cleaning up
Clear all uncommitted changes:
git reset --hard
Delete all untracked files and directories:
git clean -f -d
Visualization
Display a graphical one-line-per-commit representation of all branches and commits:
git log --oneline --decorate --graph --all
Display the commits that contain the matching text (use -i to ignore case and --no-merges to exclude merges):
git log -p -S"console.log"
Display the commits and changes associated with a specific file:
git log -p README.md
Display the commits and changes associated with a file after a certain date:
git log -p --after="2 weeks ago" README.md
Find a breaking commit with bisect
Begin a bisect session:
git bisect start
Mark the current commit as broken:
git bisect bad
Mark the current commit as healthy, and check out the next testable commit:
git bisect good
Test the commit and run git bisect bad or git bisect good. Keep testing and marking until you are left with the commit that first introduced the bug.
Reset your repository to the original state:
git bisect reset