First-time 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
Daily basics
| Command | What it does |
|---|---|
git status -sb | Short status with the current branch |
git add -p | Stage changes hunk by hunk |
git commit -m "msg" | Commit staged changes |
git diff --staged | Show what is about to be committed |
git pull | Fetch and integrate remote changes |
git push -u origin HEAD | Push the current branch and set upstream |
Branches
git switch -c feature/login # create and switch
git switch main # switch back
git branch -vv # list with upstream info
git merge feature/login # merge into current branch
git branch -d feature/login # delete a merged branch
Undoing things
| Situation | Command |
|---|---|
| Discard changes in a file | git restore file.txt |
| Unstage a file | git restore --staged file.txt |
| Fix the last commit message | git commit --amend |
| Undo last commit, keep changes | git reset --soft HEAD~1 |
| Revert a pushed commit | git revert <sha> |
| Find a "lost" commit | git reflog |
Prefer git revert for commits that are already shared. Rewriting public history with reset or rebase forces everyone else to recover.
Stash
git stash push -m "wip: parser" # save work in progress
git stash list
git stash pop # reapply and drop the latest
git stash push -u # include untracked files
Reading and tidying history
git log --oneline --graph --decorate --all
git log -p -- path/to/file # history of one file
git blame -L 10,30 app.py # who changed these lines
git rebase -i HEAD~4 # squash, reword, reorder
In an interactive rebase, change pick to squash (or s) to fold a commit into the previous one, or reword to edit just the message.