Git

The everyday subset of Git: set up, branch, commit, fix mistakes, and share your work.

Getting started

git init
Create a new repository in the current folder
git clone <url>
Copy a remote repository locally
git status
Show changed, staged and untracked files
git log --oneline --graph
Compact history with branch structure

Staging & committing

git add -p
Stage changes hunk by hunk (interactive)
git commit -m "msg"
Commit staged changes with a message
git commit --amend
Fold staged changes into the last commit
git diff --staged
See exactly what will be committed

Branching

git switch -c feature
Create and move to a new branch
git switch main
Move to an existing branch
git branch -d feature
Delete a merged branch (-D to force)
git merge feature
Merge a branch into the current one
git rebase main
Replay your commits on top of main

Undoing things

git restore file
Discard unstaged changes to a file
git restore --staged file
Unstage, keep the edits
git reset --soft HEAD~1
Undo last commit, keep changes staged
git revert <sha>
New commit that reverses an old one (safe on shared branches)
git reflog
Find "lost" commits after a bad reset

Remotes

git fetch --prune
Download remote changes, drop stale branches
git pull --rebase
Fetch and rebase instead of creating merge commits
git push -u origin feature
Push and set upstream for the branch
git push --force-with-lease
Safer force push after a rebase

Stash & cherry-pick

git stash -u
Shelve changes incl. untracked files
git stash pop
Re-apply and drop the latest stash
git cherry-pick <sha>
Apply a single commit onto the current branch
git bisect start
Binary-search history for the commit that broke things
Tip: Add git config --global alias.lg "log --oneline --graph --decorate --all" once and enjoy git lg forever.

A typical feature workflow

# start from fresh main
git switch main && git pull --rebase
git switch -c feat/search-box

# work, then commit in small pieces
git add -p
git commit -m "Add search box to header"

# keep up to date and publish
git fetch origin
git rebase origin/main
git push -u origin feat/search-box