Git

Everyday Git commands for committing, branching, syncing and undoing changes.

Version Control #cli#git#vcs Last updated
Library

Setup#

git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
git config --global pull.rebase true      # rebase instead of merge on pull
git config --list --show-origin           # where each setting comes from

Start a repository#

Command Description
git init Create a repository in the current directory
git clone <url> Copy a remote repository
git clone --depth 1 <url> Shallow clone (latest commit only)

Stage and commit#

git status -sb                 # short status with branch info
git add file.txt               # stage a file
git add -p                     # stage interactively, hunk by hunk
git commit -m "Add feature"    # commit staged changes
git commit --amend --no-edit   # add staged changes to the last commit
git diff                       # unstaged changes
git diff --staged              # staged changes

Branches#

git switch -c feature/login    # create and switch to a branch
git switch main                # switch branches
git branch -vv                 # list branches with upstream info
git branch -d feature/login    # delete a merged branch
git merge feature/login        # merge into the current branch
git rebase main                # replay current branch on top of main

Remotes and syncing#

git remote -v                          # list remotes
git fetch --prune                      # update remote refs, drop deleted ones
git pull                               # fetch + integrate
git push -u origin feature/login       # push and set upstream
git push --force-with-lease            # safer force push

Inspect history#

git log --oneline --graph --decorate --all
git log -p -- path/to/file             # history of one file with diffs
git blame -L 10,20 file.go             # who changed lines 10-20
git show <commit>                      # details of one commit
git reflog                             # every position HEAD has been

Undo things#

Situation Command
Discard unstaged changes in a file git restore file.txt
Unstage a file git restore --staged file.txt
Undo last commit, keep changes git reset --soft HEAD~1
Revert a pushed commit git revert <commit>
Recover a lost commit git reflog then git switch -c rescue <sha>

Stash#

git stash push -m "wip: refactor"   # save work in progress
git stash list
git stash pop                       # re-apply and drop the latest stash

Tags#

git tag -a v1.2.0 -m "Release 1.2.0"
git push origin v1.2.0

Back to library

Keyboard shortcuts

/
Focus search
Esc
Close dialogs, menus and messages
?
Show this help
Ctrl S
Save in the admin editor