git· 5 min read

Git everyday commands

The commands that cover most days of work with Git, plus a few safe ways to undo things.

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

CommandWhat it does
git status -sbShort status with the current branch
git add -pStage changes hunk by hunk
git commit -m "msg"Commit staged changes
git diff --stagedShow what is about to be committed
git pullFetch and integrate remote changes
git push -u origin HEADPush 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

SituationCommand
Discard changes in a filegit restore file.txt
Unstage a filegit restore --staged file.txt
Fix the last commit messagegit commit --amend
Undo last commit, keep changesgit reset --soft HEAD~1
Revert a pushed commitgit revert <sha>
Find a "lost" commitgit 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.