Browse cheat sheets · Git

Technology: GitCategory: Version ControlDifficulty: BeginnerUpdated

Everyday Git Commands

Use the Git commands engineers need most often for inspecting changes, creating commits, syncing branches, reviewing history, and recovering from common local mistakes.

On this page
  1. Problem
  2. Quick answer
  3. Code / commands
  4. 1. Check the current repository state
  5. 2. Show a compact status
  6. 3. See unstaged changes
  7. 4. See staged changes
  8. 5. Show both staged and unstaged context
  9. 6. Create and switch to a new branch
  10. 7. Switch to an existing branch
  11. 8. List local branches
  12. 9. Rename the current branch
  13. 10. Stage one file
  14. 11. Stage several known files
  15. 12. Stage all current changes
  16. 13. Stage interactively
  17. 14. Unstage a file without discarding its edits
  18. 15. Commit staged changes
  19. 16. Inspect the commit before pushing
  20. 17. Amend the most recent local commit
  21. 18. Fetch remote updates without changing your files
  22. 19. Inspect what changed on the remote main branch
  23. 20. Update your local main branch
  24. 21. Rebase a feature branch onto updated main
  25. 22. Merge main into the feature branch
  26. 23. Push a new branch
  27. 24. Push later commits
  28. 25. Prefer force-with-lease over force
  29. 26. Never force-push shared protected branches casually
  30. 27. View recent history
  31. 28. Show commits for one file
  32. 29. See who changed specific lines
  33. 30. Compare your branch with main
  34. 31. Compare two commits
  35. 32. Restore an unstaged file to the last committed version
  36. 33. Restore one file from another commit
  37. 34. Revert a shared commit safely
  38. 35. Do not confuse revert with reset
  39. 36. Move HEAD back while keeping changes staged
  40. 37. Move HEAD back and keep changes unstaged
  41. 38. Avoid reset --hard unless you are certain
  42. 39. Temporarily stash local changes
  43. 40. Stash tracked and untracked files
  44. 41. List stashes
  45. 42. Inspect a stash before applying it
  46. 43. Apply a stash without deleting it
  47. 44. Apply and remove a stash
  48. 45. Delete a stash deliberately
  49. 46. Delete a merged local branch
  50. 47. Force-delete a local branch only when intentional
  51. 48. Delete a remote branch
  52. 49. See configured remotes
  53. 50. Inspect upstream tracking
  54. 51. Set an upstream manually
  55. 52. Show repository root
  56. 53. Show current branch name
  57. 54. Show current commit
  58. 55. Check whether the working tree is clean in automation
  59. 56. Fetch and prune deleted remote branches
  60. 57. See commits unique to your branch
  61. 58. See changed files relative to main
  62. 59. Search commit messages
  63. 60. Find commits that changed a string
  64. 61. Find commits whose patch matches a pattern
  65. 62. Show one commit
  66. 63. Cherry-pick one known commit
  67. 64. Abort a conflicted cherry-pick
  68. 65. Abort a rebase
  69. 66. Continue a rebase after resolving conflicts
  70. 67. Abort a merge
  71. 68. Inspect conflict markers
  72. 69. Use reflog to recover local history
  73. 70. Create a safety branch before risky local history edits
  74. What the result means
  75. What to look for
  76. git status shows staged and unstaged changes for the same file
  77. Push is rejected
  78. Commit contains unrelated files
  79. Merge or rebase created conflicts
  80. You lost a local commit after reset/rebase
  81. Feature branch contains unexpected commits
  82. Production notes
  83. Shared history should be treated as immutable by default
  84. --force-with-lease is safer, not risk-free
  85. Git does not automatically protect uncommitted work from every command
  86. A clean working tree simplifies risky operations
  87. Small focused commits improve recovery
  88. Git history is part of production engineering
  89. Common mistakes
  90. 1. Running git add . without checking status
  91. 2. Committing without reviewing git diff --cached
  92. 3. Using git pull without understanding the configured strategy
  93. 4. Using git push --force
  94. 5. Using git reset --hard as general cleanup
  95. 6. Amending commits already shared with teammates
  96. 7. Deleting a branch before checking unique commits
  97. 8. Treating git stash as permanent storage
  98. 9. Using git blame to assign fault
  99. 10. Assuming a rejected push means force push is required
  100. Next step
  101. Related deep dives

Problem

You use Git every day but do not want to memorize every command or risk using a destructive one at the wrong time.

Most engineering workflows repeatedly need to:

  • inspect what changed
  • create or switch branches
  • stage selected files
  • commit work
  • update from the remote
  • push a branch
  • compare changes
  • inspect history
  • discard or restore local edits safely
  • recover from a small local mistake

The goal is to use a small set of reliable commands with a clear understanding of what each one changes.

Quick answer

For a normal feature branch:

git status
git switch -c feature/my-change
git add path/to/file
git diff --cached
git commit -m "Describe the change"
git fetch origin
git rebase origin/main
git push -u origin feature/my-change

Before any command that changes history or removes work, run:

git status
git diff
git log --oneline --decorate -10

The safest habit is:

inspect
→ stage intentionally
→ review staged diff
→ commit
→ sync
→ push

Code / commands

1. Check the current repository state

git status

Use this first.

It shows:

  • current branch
  • staged files
  • modified files
  • untracked files
  • whether the branch is ahead/behind its upstream

Before resetting, restoring, rebasing, or switching branches, check git status.


2. Show a compact status

git status --short

Typical output:

 M src/app.py
M  README.md
?? notes.txt

Interpretation:

left column  = staged state
right column = working-tree state
??           = untracked

A file can have both staged and unstaged changes at the same time.


3. See unstaged changes

git diff

This compares:

working tree
vs
index/staging area

Use it before staging.


4. See staged changes

git diff --cached

Equivalent:

git diff --staged

This compares:

staging area
vs
HEAD

Run this before committing.

It answers:

What exactly will this commit contain?

5. Show both staged and unstaged context

git diff
git diff --cached

There is no single substitute for understanding both states.

A common mistake is reviewing only the working-tree diff while forgetting already staged changes.


6. Create and switch to a new branch

git switch -c feature/report-engine

This creates:

feature/report-engine

from the current commit and switches to it.

Prefer git switch for branch switching on modern Git versions.


7. Switch to an existing branch

git switch main

Older equivalent:

git checkout main

checkout still works, but switch makes branch intent clearer.


8. List local branches

git branch

Show local and remote-tracking branches:

git branch -a

Show tracking information:

git branch -vv

9. Rename the current branch

git branch -m new-branch-name

If the old branch was already pushed, renaming the local branch does not automatically rename the remote branch.

Handle remote cleanup separately and deliberately.


10. Stage one file

git add src/app.py

Use this when you want the commit scope to stay explicit.


11. Stage several known files

git add src/app.py src/config.py README.md

This is safer than staging everything when unrelated work exists in the repository.


12. Stage all current changes

git add -A

This stages:

  • new files
  • modified files
  • deletions

Use only after checking:

git status

and reviewing whether every change belongs in the same commit.


13. Stage interactively

git add -p

Use this when one file contains changes for multiple logical commits.

Git will let you stage hunks selectively.

This is one of the most useful commands for keeping commits focused.


14. Unstage a file without discarding its edits

git restore --staged src/app.py

This moves the file out of the staging area.

Your working-tree edits remain.

Use this if you staged the wrong file.


15. Commit staged changes

git commit -m "Add pipeline retry handling"

Commit messages should describe the change, not the act of editing.

Prefer:

Add pipeline retry handling

over:

Changes

16. Inspect the commit before pushing

git show --stat

Show the full patch:

git show

This displays the current HEAD commit by default.


17. Amend the most recent local commit

If you forgot to stage one file:

git add src/config.py
git commit --amend --no-edit

Or change the message:

git commit --amend

Use amend freely for a commit that has not been shared.

If the commit is already on a shared branch, amending rewrites history and may require a force push.


18. Fetch remote updates without changing your files

git fetch origin

This updates remote-tracking references such as:

origin/main
origin/develop

It does not merge or rebase your current branch.

This makes fetch a safe first step before deciding how to synchronize.


19. Inspect what changed on the remote main branch

git log --oneline HEAD..origin/main

This shows commits on origin/main that are not in your current branch.

To see commits your branch has that origin/main does not:

git log --oneline origin/main..HEAD

20. Update your local main branch

git switch main
git pull --ff-only

--ff-only refuses to create an unexpected merge commit.

If local main has diverged, Git stops and lets you investigate instead of making an automatic merge.


21. Rebase a feature branch onto updated main

git fetch origin
git rebase origin/main

Use this when your team prefers linear feature-branch history.

Conceptually:

your commits
→ replayed on top of latest origin/main

Do not casually rebase commits that other people are already building on.


22. Merge main into the feature branch

Alternative to rebase:

git fetch origin
git merge origin/main

Use this when merge-based history is preferred or when rewriting branch history is undesirable.

The choice between merge and rebase is a team workflow decision.


23. Push a new branch

git push -u origin feature/report-engine

-u sets the upstream.

After that, usually:

git push

is enough.


24. Push later commits

git push

If Git says the remote contains work you do not have, do not immediately force push.

Fetch and inspect the divergence.


25. Prefer force-with-lease over force

If you intentionally rebased your own remote feature branch:

git push --force-with-lease

Prefer this over:

git push --force

--force-with-lease refuses to overwrite the remote branch if it changed in a way your local repository does not expect.

Still use it carefully.


26. Never force-push shared protected branches casually

Avoid rewriting:

main
master
develop
release branches
shared team branches

unless your repository workflow explicitly requires it.

History rewriting on shared branches can disrupt other developers and CI/CD.


27. View recent history

git log --oneline -10

With branch/tag decoration:

git log --oneline --decorate -10

Include graph:

git log --oneline --graph --decorate --all -20

This is useful for understanding branch relationships.


28. Show commits for one file

git log --oneline -- src/app.py

Show patches:

git log -p -- src/app.py

Use this to investigate when and why a file changed.


29. See who changed specific lines

git blame src/app.py

Use blame as a navigation tool to find the relevant commit.

Do not treat it as proof of who “caused” a current bug; the line may have been moved or inherited from older logic.


30. Compare your branch with main

git diff origin/main...HEAD

The three-dot comparison is useful for reviewing changes introduced by your branch since the merge base with origin/main.

This is close to the change set typically reviewed in a pull request.


31. Compare two commits

git diff <commit-a> <commit-b>

Example:

git diff a1b2c3d e4f5a6b

Add:

--stat

for a summary:

git diff --stat a1b2c3d e4f5a6b

32. Restore an unstaged file to the last committed version

git restore src/app.py

Warning:

This discards unstaged changes in that file.

Run:

git diff src/app.py

first if there is any doubt.


33. Restore one file from another commit

git restore \
  --source=<commit> \
  -- path/to/file

Example:

git restore \
  --source=HEAD~1 \
  -- src/app.py

This places that version into your working tree.

It does not create a commit automatically.


34. Revert a shared commit safely

git revert <commit>

This creates a new commit that reverses the selected commit.

Use this for already-shared history because it preserves the existing commit graph.

Example:

git revert a1b2c3d

35. Do not confuse revert with reset

git revert
→ creates a new inverse commit

git reset
→ moves a branch reference and can alter staging/working state

For public/shared history, revert is usually safer.


36. Move HEAD back while keeping changes staged

git reset --soft HEAD~1

This removes the latest local commit while leaving its changes staged.

Use for local history cleanup before sharing.


37. Move HEAD back and keep changes unstaged

git reset HEAD~1

Equivalent default mode:

--mixed

The commit is removed locally, but file edits remain in the working tree.


38. Avoid reset --hard unless you are certain

git reset --hard HEAD

This discards tracked working-tree and staged changes.

It can destroy uncommitted work.

Do not use it as a routine cleanup command.

Inspect first:

git status
git diff
git diff --cached

39. Temporarily stash local changes

git stash push -m "WIP report changes"

Use when you need a clean working tree temporarily.


40. Stash tracked and untracked files

git stash push -u -m "WIP"

-u includes untracked files.

Ignored files are still excluded.


41. List stashes

git stash list

Example:

stash@{0}: On feature/report-engine: WIP

42. Inspect a stash before applying it

git stash show -p stash@{0}

Useful when you have several stashes and do not remember their contents.


43. Apply a stash without deleting it

git stash apply stash@{0}

Use this when you want to keep the stash as a backup until you confirm the result.


44. Apply and remove a stash

git stash pop

This applies the most recent stash and removes it if application succeeds cleanly.

For valuable work, apply first can be safer.


45. Delete a stash deliberately

git stash drop stash@{0}

Do not run:

git stash clear

unless you intentionally want to remove all stashes.


46. Delete a merged local branch

After confirming it is merged:

git branch -d feature/report-engine

-d refuses if Git does not consider the branch fully merged.

This is safer than -D.


47. Force-delete a local branch only when intentional

git branch -D feature/report-engine

This removes the local branch even if it contains commits not merged elsewhere.

Check first:

git log main..feature/report-engine

48. Delete a remote branch

git push origin --delete feature/report-engine

Do this after the branch is merged or no longer required.

Remote deletion affects other collaborators, so confirm branch ownership/workflow first.


49. See configured remotes

git remote -v

Useful before pushing if multiple remotes exist.


50. Inspect upstream tracking

git branch -vv

This shows whether a local branch tracks:

origin/main
origin/feature/...

and whether it is ahead or behind.


51. Set an upstream manually

git branch \
  --set-upstream-to=origin/main \
  main

Usually git push -u sets this automatically for feature branches.


52. Show repository root

git rev-parse --show-toplevel

Useful when working in nested directories and you are not sure which repository you are in.


53. Show current branch name

git branch --show-current

Useful in scripts and quick checks.


54. Show current commit

git rev-parse HEAD

Short version:

git rev-parse --short HEAD

Useful for deployment logs and build metadata.


55. Check whether the working tree is clean in automation

git status --porcelain

No output means no tracked/untracked changes Git would normally report.

Useful in scripts because the output format is stable for machine parsing.


56. Fetch and prune deleted remote branches

git fetch --prune

This removes stale remote-tracking references such as:

origin/feature/old-branch

when the branch was deleted on the remote.

It does not delete local branches.


57. See commits unique to your branch

git log --oneline origin/main..HEAD

Use before opening a pull request to confirm what your branch contributes.


58. See changed files relative to main

git diff --name-status origin/main...HEAD

Example output:

M  src/app.py
A  src/new_module.py
D  src/old_module.py

Use for quick scope review.


59. Search commit messages

git log \
  --oneline \
  --grep="pipeline"

Useful when looking for a past change by topic.


60. Find commits that changed a string

git log \
  -S "old_function_name" \
  --oneline

Use -S when you want commits that changed the number of occurrences of a specific string.

This is useful for historical debugging.


61. Find commits whose patch matches a pattern

git log \
  -G "retry.*count" \
  --oneline

-G searches the diff for a regex.

Use this for code-history investigation.


62. Show one commit

git show <commit>

Summary only:

git show --stat <commit>

Use this before reverting or cherry-picking a commit.


63. Cherry-pick one known commit

git cherry-pick <commit>

Use when one specific commit needs to be applied to another branch.

Before cherry-picking, confirm the commit is self-contained.

A cherry-pick can conflict or bring hidden dependencies on surrounding commits.


64. Abort a conflicted cherry-pick

git cherry-pick --abort

Use if the operation should be abandoned and you want to return to the pre-cherry-pick state.


65. Abort a rebase

git rebase --abort

Use when a rebase becomes unsafe or you realize you started from the wrong state.


66. Continue a rebase after resolving conflicts

After editing conflicted files:

git add path/to/resolved-file
git rebase --continue

Repeat until complete.

Do not commit conflict resolutions manually during a normal rebase unless the workflow explicitly calls for it.


67. Abort a merge

If a merge is in progress and should be abandoned:

git merge --abort

Use this instead of trying to manually reset files during an active merge.


68. Inspect conflict markers

A conflicted file can contain:

<<<<<<< HEAD
your version
=======
incoming version
>>>>>>> branch-name

Resolve the actual intended code, remove the markers, then stage the file:

git add path/to/file

Do not blindly choose “ours” or “theirs” without understanding the change.


69. Use reflog to recover local history

git reflog

This shows recent movements of HEAD and branch references in the local repository.

It is often useful after:

  • accidental reset
  • rebase
  • branch deletion
  • checkout/switch mistakes

Example recovery workflow:

git reflog
git show <old-commit>

Then create a recovery branch:

git switch -c recovery <old-commit>

70. Create a safety branch before risky local history edits

Before a complicated rebase/reset:

git branch backup-before-rewrite

Then proceed.

This is cheap insurance when manipulating unpublished local history.

What the result means

Command Changes files/history? Typical purpose
git status No Inspect state
git diff No Review unstaged edits
git diff --cached No Review staged edits
git add Staging area Select commit content
git commit History Create commit
git fetch Remote refs Inspect remote updates safely
git pull --ff-only Branch/files Fast-forward local branch only
git rebase History Replay local commits
git merge History Combine histories
git restore Working tree/index Restore file content/state
git revert History Safely reverse shared commit
git reset Branch/index/files depending on mode Rewrite local state/history
git stash Stash + working tree Temporarily set work aside
git reflog No Recover local reference history

The important distinction is:

inspect commands
→ low risk

working-tree/staging commands
→ may change uncommitted state

history-rewriting commands
→ require awareness of whether commits are already shared

What to look for

git status shows staged and unstaged changes for the same file

You staged one version and then edited the file again.

Check both:

git diff --cached
git diff

before committing.

Push is rejected

The remote branch has work you do not have.

Run:

git fetch origin

then inspect:

git log --oneline --graph --decorate HEAD origin/<branch>

Do not jump directly to force push.

Commit contains unrelated files

Use:

git restore --staged <file>

and recommit only the intended scope.

Merge or rebase created conflicts

Determine whether both branches changed the same logical code.

Resolve based on intended behavior, not simply by choosing one side mechanically.

You lost a local commit after reset/rebase

Check:

git reflog

before assuming it is gone.

Feature branch contains unexpected commits

Compare with main:

git log --oneline origin/main..HEAD

and inspect the graph.

Production notes

Shared history should be treated as immutable by default

Once commits are pushed and consumed by others, prefer:

git revert

over history rewriting.

Feature branches owned by one developer are usually safer places for rebase/amend workflows.

--force-with-lease is safer, not risk-free

It protects against overwriting remote updates you have not seen.

It still intentionally rewrites remote history.

Git does not automatically protect uncommitted work from every command

Commands such as:

git restore
git reset --hard

can discard local edits.

Inspect first.

A clean working tree simplifies risky operations

Before rebase, merge, or branch surgery:

git status

Commit or stash unrelated work.

Small focused commits improve recovery

Focused commits make it easier to:

  • review
  • revert
  • cherry-pick
  • bisect
  • understand history

Do not combine unrelated refactors and behavior changes unless there is a good reason.

Git history is part of production engineering

Commit IDs often appear in:

  • deployments
  • CI/CD
  • incident timelines
  • release notes
  • rollbacks

Use meaningful commits and avoid unnecessary rewriting of shared history.

Common mistakes

1. Running git add . without checking status

You may stage unrelated files, generated files, or secrets.

2. Committing without reviewing git diff --cached

The commit may contain more or less than intended.

3. Using git pull without understanding the configured strategy

Depending on configuration, pull may merge or rebase.

For protected local main branches, git pull --ff-only is often more predictable.

4. Using git push --force

Prefer --force-with-lease when rewriting your own remote branch is genuinely required.

5. Using git reset --hard as general cleanup

It can permanently discard uncommitted tracked changes.

6. Amending commits already shared with teammates

This changes commit IDs and can disrupt their branches.

7. Deleting a branch before checking unique commits

Inspect:

git log main..branch-name

first.

8. Treating git stash as permanent storage

Stashes are temporary working-state snapshots, not a durable branching strategy.

9. Using git blame to assign fault

Use it to find historical context and relevant commits.

10. Assuming a rejected push means force push is required

Usually it means you should fetch and understand the remote changes first.

Next step

Use the situation to choose the next command.

  • Unsure what changed → git status, git diff, git diff --cached.
  • Need a new feature branch → git switch -c <branch>.
  • Need a focused commit → git add -p, then git diff --cached.
  • Need latest remote state without changing local files → git fetch.
  • Need to update local main safely → git pull --ff-only.
  • Need feature branch on latest main → rebase or merge according to team policy.
  • Push rejected → fetch and inspect divergence before deciding.
  • Need to undo a shared commit → git revert.
  • Need to fix the latest unshared commit → git commit --amend.
  • Need to temporarily set work aside → git stash push.
  • Think a local commit was lost → inspect git reflog.
  • Need more advanced branch/history workflows → move to Branching and Merging, Rebase Quick Reference, Undo Changes Safely, or Git Stash.

← All cheat sheets