Programming

Git cheat sheet: everyday commands with fewer surprises

Use this as a reference while working, not as a script to run from top to bottom.

A floating dark terminal card and a clean three-node Git branch path with one merge

Use this as a reference while working, not as a script to run from top to bottom. Each command acts on the repository and branch you are currently using.

Inspect the state first#

shell
git status
git diff
git diff --staged
git log --oneline --graph --decorate -10

git diff compares the working tree with the index. git diff --staged compares the index with the current commit. Reading both avoids accidentally committing an unrelated edit.

Start or copy a repository#

shell
git init project-name
git clone https://example.com/team/project.git

These are alternatives, not consecutive setup steps. Use an actual repository URL when cloning. Configure the identity appropriate to the project; git config user.name and git config user.email without --global apply to the current repository.

Stage a deliberate change#

shell
git add -- path/to/file
git diff --staged
git commit -m "Explain the change"

The -- separates options from paths. To remove a file's changes from the staging area while keeping the working edit:

shell
git restore --staged -- path/to/file

Branch and synchronize#

shell
git switch -c topic-name
git fetch origin
git log --oneline HEAD..origin/main

Replace the remote and branch with those the repository actually uses. Fetch updates remote-tracking references; it does not automatically merge the fetched work into your current branch. Inspect before deciding whether to merge or rebase.

Undo with the intended scope#

git revert COMMIT records a new commit that reverses another commit. git restore PATH can discard uncommitted edits in a file. git reset --hard can discard work and move the branch; it is not a routine “unstage” command.

If you use a stash, prefer inspecting it and applying it before deciding to drop it. Reflog can help locate local reference movements, but it is not a backup of every uncommitted edit.

For exact options, use the official Git reference. The distinction between the working tree, index and commit is more useful than memorizing a long list of destructive shortcuts.