Eric Nishio

Git Command Line Cheat Sheet

CLI

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:

bash
git remote add origin git@github.com:username/my-repo.git

Push and set up an upstream reference for a branch (first time only):

bash
git push -u origin my-branch

Committing

Interactively stage changes hunk-by-hunk:

bash
git add --patch

Amend the most recent commit:

bash
git commit --amend

Amend the most recent commit without editing the message:

bash
git commit --amend --no-edit

Branching

Create and check out a new branch:

bash
git checkout -b my-branch

Checks out a remote branch:

bash
git fetch && git checkout my-branch

Delete a branch locally:

bash
git branch -d my-branch

Delete a branch remotely:

bash
git push origin :my-branch

List remote branches:

bash
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:

bash
git stash save my-stash

List your stashes:

bash
git stash list

Restore a stash at index 0:

bash
git stash apply 0

Delete a stash at index 0:

bash
git stash drop 0

Tags

Create a new tag:

bash
git tag 1.0.0

Push all tags to origin:

bash
git push origin --tags

Delete a tag locally:

bash
git tag -d 1.0.0

Delete a tag remotely:

bash
git push origin :refs/tags/1.0.0

Cleaning up

Clear all uncommitted changes:

bash
git reset --hard

Delete all untracked files and directories:

bash
git clean -f -d

Visualization

Display a graphical one-line-per-commit representation of all branches and commits:

bash
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):

bash
git log -p -S"console.log"

Display the commits and changes associated with a specific file:

bash
git log -p README.md

Display the commits and changes associated with a file after a certain date:

bash
git log -p --after="2 weeks ago" README.md

Find a breaking commit with bisect

Begin a bisect session:

bash
git bisect start

Mark the current commit as broken:

bash
git bisect bad

Mark the current commit as healthy, and check out the next testable commit:

bash
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:

bash
git bisect reset
Japanese Wax Seal: NishioCopyright 2024 Eric Nishio
XInstagramGitHubLinkedIn