Setup
git config --global user.name "Name"
git config --global user.email "email"
git config --global core.editor "code --wait"
git config --global pull.rebase true # rebase on pull by default
Everyday
git status
git add -p # interactive hunk staging
git commit -m "msg"
git commit --amend --no-edit # amend last commit, keep message
git push -u origin HEAD # push current branch, set upstream
Branching
git switch -c feature/name # create + switch
git switch main
git branch -d feature/name # delete local
git push origin --delete feature/name # delete remote
git branch -vv # show tracking info
Rebase
git rebase main # rebase current branch onto main
git rebase -i HEAD~3 # interactive: squash/edit last 3
git rebase --onto new-base old-base branch # transplant commits
git rebase --abort
git rebase --continue
Stash
git stash push -m "wip: description"
git stash list
git stash pop # apply latest + drop
git stash apply stash@{1} # apply without dropping
git stash drop stash@{1}
Diff & Log
git diff HEAD # all unstaged changes
git diff --staged # staged only
git log --oneline --graph --all # visual branch graph
git log --follow -p -- path/to/file # full history of a file
git show <sha>
Undo
git restore file.txt # discard working tree change
git restore --staged file.txt # unstage
git reset HEAD~1 # undo last commit, keep changes staged
git reset --hard HEAD~1 # undo last commit, discard changes
git revert <sha> # safe undo via new commit
Remote
git remote -v
git fetch --prune # sync + remove stale remote refs
git pull --rebase
git push --force-with-lease # safer force push
git tag <tag_name> # mark a commit (lightweight)
git tag -a v1.0.0 -m "Release v1.0.0" # annotated tag
git push origin <tag_name> # push single tag
git push origin --tags # push all tags
git tag -d <tag_name> # delete local tag
git push origin --delete <tag_name> # delete remote tag
Bisect
git bisect start
git bisect bad # current commit is broken
git bisect good <sha> # last known good commit
# git checks out midpoint — test, then:
git bisect good # or: git bisect bad
git bisect reset # exit bisect mode
Blame & Reflog
git blame <file> # see who last edited each line
git reflog # history of all HEAD movements (incl. deleted)
git reflog show <branch> # reflog for a specific branch
Useful One-liners
# Delete all local branches already merged into main
git branch --merged main | grep -v "^\* \|main" | xargs git branch -d
# Find commit that introduced a string
git log -S "search string" --oneline
# Show files changed in last commit
git show --stat HEAD
# Cherry-pick a single commit
git cherry-pick <sha>
Hooks (.git/hooks/)
| Hook | Trigger |
|---|
pre-commit | before commit message prompt |
commit-msg | validate the commit message |
pre-push | before push |
post-merge | after merge/pull |