Git cheatsheet
What is a Git Memo?
Git is the version control system used by almost every software team. Most daily work needs only a couple of dozen commands, but the ones you need for fixing mistakes are easy to forget. This cheat sheet groups the essential commands by task, with short explanations.
Setup
git config --global user.name 'Your Name'anduser.emailset your identity.git initcreates a repository;git clone URLcopies one.
Everyday workflow
git statusshows changed and staged files.git add -pstages changes hunk by hunk.git commit -m 'message'records a snapshot.git pull --rebasefetches and replays your work on top of the remote.git push -u origin feature-xpublishes a new branch.
Branches
git switch -c feature-xcreates and switches to a branch.git merge mainmerges main into the current branch.git rebase mainreplays your commits on top of main for a linear history.git branch -d feature-xdeletes a merged branch.
Undoing things
git restore filediscards unstaged changes to a file.git restore --staged fileunstages it.git commit --amendedits the last commit (only before pushing).git revert COMMITcreates a new commit that undoes an old one; safe on shared branches.git reset --soft HEAD~1undoes the last commit but keeps the changes staged.git refloglists where HEAD has been, so you can recover lost commits.
Stash and inspect
git stashandgit stash popshelve and restore work in progress.git log --oneline --graphshows compact history.git diff --stagedshows what will be committed.
A word on force pushing
Use git push --force-with-lease instead of --force. It refuses to overwrite remote commits you have not seen.
Frequently Asked Questions
How do I undo the last commit but keep my changes?
Use git reset --soft HEAD~1. The commit is removed and the changes stay staged.
What is the difference between merge and rebase?
Merge combines histories with a merge commit. Rebase replays your commits on top of another branch for a linear history.
How do I recover a deleted commit?
Run git reflog to find the commit hash, then create a branch at it or reset to it.
Why use force-with-lease instead of force?
It only overwrites the remote branch if nobody else has pushed to it since your last fetch.