How to use the cheat sheet
- Type what you want to do, such as
undo,renameorstash. - Click a command to copy it.
- Replace the parts in angle brackets, such as
<branch>, with your own names.
The three places your changes live
Git keeps your work in three places. The working folder holds the files you edit. The staging area holds the changes you have picked for the next commit with git add. The repository holds the commits themselves. Most confusion goes away once you know which of the three a command touches: git restore changes the working folder, git restore --staged changes the staging area, and git reset moves commits.
Undoing things safely
| You want to | Use |
|---|---|
| Fix the message of the last commit | git commit --amend |
| Undo the last commit but keep the work | git reset --soft HEAD~1 |
| Undo a commit that is already pushed | git revert <commit> |
| Throw away changes to one file | git restore <file> |
| Get back a commit you lost | git reflog, then git switch -c rescue <commit> |
Commands with --hard or clean delete work that was never committed, and Git cannot bring that back. Run git status first.
Merge or rebase?
git merge joins two branches with a merge commit and leaves history as it happened. git rebase rewrites your commits so they sit on top of the other branch, which gives a straight line of history. A simple rule: rebase your own branch before sharing it, and never rebase commits other people already have.
Need to keep files out of a repository? Use the .gitignore generator. To compare two versions of a file outside Git, try the diff and merge tool. There is also a regex cheat sheet.
Frequently asked questions
How do I undo the last commit in Git?
Run git reset --soft HEAD~1 to undo it and keep your changes. If the commit is already pushed, use git revert instead so you do not rewrite shared history.
What is the difference between git fetch and git pull?
Fetch downloads new commits and leaves your files alone. Pull does a fetch and then merges the new commits into your branch.
What is the difference between git switch and git checkout?
They do the same job for branches. Switch is the newer command and only changes branches, which makes it harder to lose work by accident.
How do I delete a branch?
Use git branch -d name for a local branch and git push origin --delete name for the copy on the remote.
Is git push --force safe?
Plain --force can erase commits someone else pushed. Use --force-with-lease, which refuses to push if the remote has changed.