Git Cheatsheet
Practical Git commands for real-world workflows: committing, branching, syncing, and recovering from mistakes.
Everyday Workflow
git statusShow what changed and what’s staged.
git add <file>Stage a specific file.
git add -pInteractively stage chunks (great for clean commits).
git commit -m "message"Create a commit with a message.
git commit --amendAmend the last commit (message and staged changes).
git log --oneline --graph --decorate --allCompact, visual commit history with branches.
Branches and Remotes
git branchList local branches;
* marks current.git branch -aList local and remote branches.
git switch -c <branch>Create and switch to a new branch.
git switch <branch>Switch to an existing branch.
git push -u origin <branch>Create branch on remote and set upstream.
git fetch [--all]Update remote-tracking branches without merging.
git pull --rebaseFetch + rebase your work on top of remote (avoids merge bubbles).
Undo and Fix-Ups
Warning: Commands that rewrite history (like reset --hard or push --force) are dangerous on shared branches. Prefer revert on main.
git restore <file>Throw away unstaged changes in a file (reset to HEAD).
git restore --staged <file>Unstage a file (keep changes in working tree).
git revert <commit>Create a new commit that undoes a specific commit (safe for shared history).
git reset --soft HEAD~1Uncommit last commit but keep all changes staged.
git reset --mixed HEAD~1Uncommit and unstage last commit, keep changes in working tree.
git reset --hard HEAD~1Drop last commit and all related changes (destructive).
Stashing and Cleaning
git stash push -m "msg"Stash current changes with a label.
git stash listShow stashes with their indices.
git stash show -p stash@{0}Preview what a stash contains.
git stash apply [stash@{n}]Apply a stash, keep it in the list.
git stash popApply the latest stash and drop it.
git clean -fdRemove untracked files and directories (
-n for dry run).Rebasing and History Editing
git rebase mainReplay current branch on top of
main.git rebase -i HEAD~5Interactively edit, squash, or drop the last 5 commits.
git rebase --continueContinue rebase after resolving conflicts.
git rebase --abortAbort the rebase and return to previous state.
git push --force-with-leaseForce-push safely after rewriting history (checks remote head).