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' and user.email set your identity.
  • git init creates a repository; git clone URL copies one.

Everyday workflow

  • git status shows changed and staged files.
  • git add -p stages changes hunk by hunk.
  • git commit -m 'message' records a snapshot.
  • git pull --rebase fetches and replays your work on top of the remote.
  • git push -u origin feature-x publishes a new branch.

Branches

  • git switch -c feature-x creates and switches to a branch.
  • git merge main merges main into the current branch.
  • git rebase main replays your commits on top of main for a linear history.
  • git branch -d feature-x deletes a merged branch.

Undoing things

  • git restore file discards unstaged changes to a file.
  • git restore --staged file unstages it.
  • git commit --amend edits the last commit (only before pushing).
  • git revert COMMIT creates a new commit that undoes an old one; safe on shared branches.
  • git reset --soft HEAD~1 undoes the last commit but keeps the changes staged.
  • git reflog lists where HEAD has been, so you can recover lost commits.

Stash and inspect

  • git stash and git stash pop shelve and restore work in progress.
  • git log --oneline --graph shows compact history.
  • git diff --staged shows 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.