Skip to content

Git Cheat Sheet

The Git commands you actually use, grouped by task.

A working reference for the Git commands that come up day to day — not every flag, just the ones worth remembering. Grouped by what you are trying to do: stage and commit, branch and merge, sync with a remote, or undo a mistake.

The recovery section is the one to bookmark. Most “I broke my repo” moments are fixed with `git reflog`, `git restore`, or `git reset` — knowing which one avoids losing work.

Setup & config

git config --global user.name "Name"Set the name attached to your commits.
git config --global user.email "you@x.com"Set the commit email (match your Git host).
git config --global init.defaultBranch mainMake new repos start on `main`.
git initTurn the current directory into a repo.
git clone <url>Copy a remote repo locally with history.

Stage & commit

git statusShow staged, unstaged, and untracked files.
git add <file> · git add -AStage one file, or everything (incl. deletions).
git add -pStage selected hunks interactively.
git commit -m "message"Commit staged changes.
git commit --amendRewrite the last commit (message or contents).
git diff · git diff --stagedSee unstaged changes, or what is staged.

Branch & merge

git branchList local branches (current one starred).
git switch -c <name>Create a branch and switch to it.
git switch <name>Switch to an existing branch.
git merge <name>Merge a branch into the current one.
git rebase <base>Replay your commits on top of another branch.
git branch -d <name>Delete a merged branch (-D to force).

Remote & sync

git remote -vList configured remotes and URLs.
git fetchDownload remote changes without merging.
git pullFetch and merge the tracked remote branch.
git push · git push -u origin <name>Push; -u sets upstream on first push.
git push --force-with-leaseForce-push safely (aborts if remote moved).

Undo & recover

From least to most destructive — pick the smallest one that fits.

git restore <file>Discard unstaged changes to a file.
git restore --staged <file>Unstage a file, keep the changes.
git revert <commit>Create a new commit that undoes one (safe on shared history).
git reset --soft HEAD~1Undo last commit, keep changes staged.
git reset --hard <commit>Reset branch and working tree — discards changes.
git reflogShow where HEAD has been — recover “lost” commits.

Frequently asked questions

What is the difference between git reset and git revert?

`git revert` creates a new commit that undoes a previous one, leaving history intact — it is safe to use on branches others have pulled. `git reset` moves the branch pointer backward and can discard commits, so it is meant for local history you have not shared yet.

How do I recover a commit I lost with git reset --hard?

Run `git reflog` to list recent positions of HEAD, find the commit hash you want back, then `git reset --hard <hash>` (or `git checkout <hash>`). Reflog keeps entries for ~90 days by default, so most “lost” commits are recoverable.