Overview
Git is the universal version control system for software projects. This cheat sheet groups the commands you will use most often by workflow stage, from initial setup through advanced history manipulation.
Initial Setup
git config --global user.name "Your Name"
git config --global user.email "you@example.com"
git config --global init.defaultBranch main
git config --list
Starting a Repository
| Command | Purpose |
git init | Create a new repository in the current directory |
git clone url | Clone a remote repository |
git clone --depth 1 url | Shallow clone for faster checkout |
Everyday Workflow
git status
git add file.txt
git add .
git commit -m "Add login validation"
git pull
git push
Branching
| Command | Purpose |
git branch | List local branches |
git branch -a | List local and remote branches |
git switch -c feature/login | Create and switch to a new branch |
git switch main | Switch to an existing branch |
git branch -d feature/login | Delete a merged branch |
git merge feature/login | Merge a branch into the current one |
Undoing Changes
| Command | Effect |
git restore file.txt | Discard unstaged changes in a file |
git restore --staged file.txt | Unstage a file |
git commit --amend | Modify the last commit message or contents |
git reset --soft HEAD~1 | Undo last commit, keep changes staged |
git reset --hard HEAD~1 | Undo last commit and discard changes |
git revert abc123 | Create a new commit that undoes a previous one |
reset rewrites history and is safe only on unpushed commits. revert creates a new commit and is the safe option for shared branches.
Viewing History
git log --oneline --graph --decorate
git log -p file.txt
git log --author="Alice"
git blame file.txt
git show abc123
Stashing
git stash
git stash list
git stash pop
git stash apply stash@{2}
Remotes
git remote -v
git remote add origin https://github.com/user/repo.git
git remote set-url origin git@github.com:user/repo.git
git fetch --all --prune
Fixing Mistakes Reference
| Situation | Command |
| Wrong commit message (not pushed) | git commit --amend |
| Committed to the wrong branch | git cherry-pick then git reset |
| Need to undo a pushed commit | git revert abc123 |
| Lost commits after reset | git reflog |