Home › Guides › Git commands cheat sheet
Tech Explained · 2026Git Commands Cheat Sheet 2026: 40 Commands, Worked Examples and How to Undo Almost Anything
A Git commands cheat sheet is a working reference to the 40 or so commands that cover almost all day-to-day version control: staging and committing, branching and merging, inspecting history, syncing with a remote, and undoing mistakes. The commands below are grouped by the four places Git keeps your files.
- Four places, not one. Every command moves files between the working tree, the index, the local repository and the remote. Learn the map and the commands stop needing memorisation.
- Use switch and restore, not checkout. Git 2.51 removed the experimental label from both, so the split-up commands are now the ones to learn first.
- Your undo window is 90 days. The git-reflog documentation defaults gc.reflogExpire to 90 days, which is why almost nothing you commit locally is ever truly lost.
- force-with-lease, never force. One flag is the difference between rewriting your branch and silently deleting a colleague's commits.
- Run git maintenance start once per big repo. It schedules commit-graph and prefetch hourly and quietly keeps log and status fast.
- Git is still moving. 2.52 shipped git last-modified and git repo info, 2.54 shipped git history reword, 2.55 brought fsmonitor to Linux.
You force-pushed to the shared branch at 7pm on a Friday, and the teammate who pushed twenty minutes earlier now has no commits. This page exists to prevent that, and to fix it if you are already there. Most Git references list commands alphabetically, which is useless when you are panicking. This one is organised the way Git behaves: by where your files are and where you want them.
How Git Actually Works: The Four Places Your Code Lives
Git tracks snapshots, and it keeps them in four places. A change starts in your working tree, the folder you see in your editor. git add copies it into the index, a scratch space holding the exact contents of your next commit. git commit freezes the index into the local repository inside .git. git push sends those objects to a remote.
Nearly every confusing Git message is a question about which of those four you meant. "Changes not staged for commit" means the working tree and index disagree. "Your branch is ahead of origin/main by 2 commits" means the local repo and the remote disagree. Read the errors that way and the right command is usually obvious.
The four areas, and the commands that move files between them
Forward arrows publish work. Return arrows undo it. Every command below is one of these arrows.
Command names checked against the official Git documentation on 28 September 2026.
Keep that diagram in your head and the rest of this page is a lookup table. Version control sits underneath every deployment pipeline you will touch, which is why it comes early in 360DT's AWS Solutions Architect and DevOps program rather than being assumed.
Git Commands Cheat Sheet: Setup, Staging and Committing
Two commands here are worth changing your habits over. git status -sb gives you the same information as bare git status in three lines instead of fifteen. git add -p walks you through changes hunk by hunk, so you stop committing debug prints by accident.
| Command | What it does | When you reach for it |
|---|---|---|
git init |
Creates a new .git directory | Starting a repo from an existing folder |
git clone <url> |
Copies a remote repo locally | Day one on any project |
git config --global user.email "you@x.com" |
Sets commit identity | Once per machine |
git status -sb |
Short status plus branch and tracking | Every few minutes |
git add -p |
Stages selected hunks interactively | One file, two unrelated changes |
git restore <file> |
Discards working-tree changes | You broke a file and want it back |
git restore --staged <file> |
Unstages without touching your edits | You added too much |
git diff / git diff --staged
|
Unstaged changes / staged changes | Reading your work before committing |
git commit --amend --no-edit |
Folds staged changes into the last commit | Forgot a file, have not pushed |
git rm --cached <file> |
Stops tracking, keeps the file on disk | The .env you committed by mistake |
git stash push -m "wip" |
Shelves changes, cleans the tree | A hotfix lands mid-task |
git stash pop |
Reapplies the latest stash | After the hotfix ships |
A worked example. Take a three-person backend team at a Pune fintech. One engineer fixes a rounding bug in payments.py and, in the same sitting, adds a debug print. Committing the file wholesale ships the print to production.
$ git status -sb
## feature/rounding...origin/feature/rounding
M payments.py
$ git add -p payments.py
# Git shows each hunk: Stage this hunk [y,n,q,a,d,s,e,?]?
# answer y for the rounding fix, n for the debug print
$ git diff --staged # confirm only the fix is staged
$ git commit -m "Fix paise rounding in settlement totals"
$ git restore payments.py # discard the leftover debug print
That git diff --staged between staging and committing is the highest-value habit on this page. Two seconds, and it catches what code review is worst at spotting.
Branching and Merging: The Git Branch Commands You Use Weekly
Here is the change most people have not made. git checkout does two unrelated jobs, switching branches and restoring files, which is precisely why it confuses beginners. Git 2.23 split it into git switch and git restore, and both sat marked experimental for six years. Git 2.51, released in August 2025, removed that label, the upstream commit noting that users had come to rely on the behaviour. Checkout is not going away, but it is no longer the command to learn first.
| Command | What it does | Note |
|---|---|---|
git switch -c feature/x |
Creates a branch and moves to it | Replaces git checkout -b
|
git switch - |
Jumps back to the previous branch | Same trick as cd -
|
git branch -vv |
Branches with tracking and last commit | Shows branches gone on the remote |
git branch -d / -D
|
Deletes merged / deletes regardless |
-D is recoverable via reflog |
git merge --no-ff feature/x |
Always creates a merge commit | Keeps the feature visible in history |
git merge --abort |
Returns to the pre-merge state | The panic button mid-merge |
git rebase -i HEAD~5 |
Rewrites the last five commits | Only on commits nobody else has pulled |
git rebase --onto main old new |
Moves a branch onto a different base | Branches cut from the wrong parent |
git cherry-pick <sha> |
Copies one commit onto this branch | Backporting a fix to a release branch |
git worktree add ../hotfix main |
Second branch in a second folder | Review a PR without stashing |
Of all the git branch commands above, git worktree is the most underused. Instead of stashing everything to review someone else's branch, you get a second directory sharing one object database, so your build cache and your half-finished work both survive.
$ git worktree add ../review-pr-482 origin/feature/refund-api
$ cd ../review-pr-482 && npm test
$ cd - && git worktree remove ../review-pr-482
Also read: What Is CI/CD? How the Pipeline Works, CI vs CD, and Your First Workflow in 2026, which picks up where a merged branch leaves off.
Reading History: git log, git blame and the New git last-modified
$ git log --oneline --graph --decorate -20 # the shape of recent history
$ git log -S "SETTLEMENT_TZ" --oneline # commits that added or removed that string
$ git log -p -- src/payments/ # full diffs, one path only
$ git blame -L 40,60 payments.py # who wrote lines 40 to 60
$ git shortlog -sn --since="6 months ago" # commit counts per author
$ git bisect start && git bisect bad && git bisect good v2.1.0
git log -S is the one to memorise: it searches diff content rather than commit messages, so when a config value changes and nobody documented it, you find the commit in seconds. git bisect is the other. Give it one bad commit and one good one and it binary-searches your history. Twenty commits become five tests.
Git 2.52 added git last-modified, which reports the most recent commit touching each path under a directory. GitHub's release highlights describe it as producing the same answer as older log-based workarounds in a fraction of the time. The official documentation flags it as experimental and warns the behaviour may change, so use it locally rather than scripting around it.
$ git last-modified src/
$ git last-modified --recursive --max-depth=2 src/payments/
-
You blame the wrong person. A whitespace reformat makes every line look freshly authored. Run
git blame -w -Mbefore you go asking questions. - You bisect with a flaky test. If the test fails intermittently, bisect confidently returns nonsense. Make the reproduction deterministic first.
-
You search messages instead of diffs.
git log --grepreads messages,git log -Sreads content. People try the first and conclude the change never happened.
Git Commands Cheat Sheet: Syncing With a Remote Safely
This is the part of any Git commands cheat sheet where you can hurt other people, so it deserves more care than the rest.
| Command | What it does | Why it matters |
|---|---|---|
git fetch --prune |
Downloads remote state, drops stale branches | Stops git branch -a listing ghosts |
git pull --rebase |
Fetches, then replays your commits on top | No noise merge commit per sync |
git push -u origin feature/x |
Pushes and sets upstream tracking | Later pushes need no arguments |
git push --force-with-lease |
Force pushes only if the remote has not moved | Refuses to overwrite new commits |
git remote -v / set-url
|
Lists or changes remote addresses | Switching HTTPS to SSH |
git ls-remote --heads origin |
Lists remote branches without cloning | Checking a repo from a CI box |
git clone --filter=blob:none <url> |
Blobless clone, contents fetched on demand | Cuts clone time on heavy history |
git maintenance start |
Registers the repo for background upkeep | Keeps log and status fast |
$ git config --global alias.pushf "push --force-with-lease"
$ git config --global pull.rebase true
$ git config --global init.defaultBranch main
That last line is worth doing now. Git 2.52 added a hint about the default branch name changing, and Git 3.0 will ship main instead of master.
git maintenance start deserves its own sentence, because almost nobody runs it. Per the official git-maintenance documentation it sets maintenance.strategy to incremental and hooks into your operating system scheduler, systemd timers on Linux or Task Scheduler on Windows, then runs commit-graph and prefetch hourly and loose-objects and incremental-repack daily, with the old gc task disabled. On a repo with years of history that is the difference between git log feeling instant and feeling like a database query. The same instinct, treating repo hygiene as a build cost rather than a preference, runs through the DevOps half of 360DT's Azure Solutions Architect and DevOps course.
How to Undo a Git Commit, and 5 Other Messes You Will Make
Almost nothing you commit is permanent. The git-reflog documentation defaults gc.reflogExpire to 90 days for reachable entries and gc.reflogExpireUnreachable to 30 days for the rest, so a branch you deleted this morning is sitting in your reflog right now. Start every recovery the same way:
$ git reflog
a1b2c3d HEAD@{0}: reset: moving to HEAD~3
9f8e7d6 HEAD@{1}: commit: Add refund reconciliation job
4c5b6a7 HEAD@{2}: checkout: moving from main to feature/refunds
$ git switch -c rescue 9f8e7d6 # the work is back, on a new branch
Six Git messes and the command that fixes each
Read the symptom, not the cause. The fix follows from where the change currently sits.
Wrong commit message
You typed the ticket number wrong and have not pushed. git commit --amend opens the message and rewrites the commit in place.
Committed too early
git reset --soft HEAD~1 removes the commit but leaves every change staged, so you can re-split it. --mixed also unstages.
Bad commit already pushed
Never reset a shared branch. git revert <sha> adds a new commit undoing the old one, so everyone else's history stays valid.
Deleted the wrong branch
git reflog, find the SHA it pointed at, then git switch -c <name> <sha>. Roughly 30 days on unreachable entries.
Local branch is a disaster
git fetch origin then git reset --hard origin/main discards everything local. Stash first if you are not certain.
Untracked junk everywhere
git clean -nd lists what would go. Only then run git clean -fd. Skipping the dry run is how people lose config files.
Reflog retention defaults confirmed against the official git-reflog documentation on 28 September 2026.
The honest caveat: the reflog is local and personal. It does not travel with a clone, it will not help the colleague whose commits your force push destroyed, and it covers nothing you never committed. A file you edited for three hours and then ran git checkout . over is gone. Git protects committed work extremely well and uncommitted work not at all, which is the real argument for committing early and often on a branch nobody else reads.
Git is step one. The AWS DevOps track is the other ninety.
A 12-week live weekend program preparing you for both AWS Solutions Architect Associate (SAA-C03) and AWS DevOps Engineer Professional (DOP-C02). Includes hands-on projects, mentor support and placement guidance.
Explore the course
Git Commands for Beginners: What to Skip in Month One
Most lists of git commands for beginners are too long to be useful. You do not need forty commands in week one. Eight carry the daily loop: clone, status -sb, add -p, commit, switch -c, pull --rebase, push -u origin and reflog. Add the rest when a situation forces you to.
An unpopular opinion: skip git flow entirely. Its develop, release and hotfix branches were designed for shipping versioned desktop software, and most teams adopting it deploy continuously from one branch. Short-lived feature branches merged into main, with tags for releases, cover what almost every Indian product team needs. You trade a little release ceremony for much less merge pain. Skip memorising git rebase --onto too. It is useful maybe four times a year, and you will look it up anyway.
This turns career-relevant the moment your commits start triggering pipelines, because branch protection and merge queues are version control questions before they are CI questions. That workflow sits in the AZ-400 material behind 360DT's certification tracks and in the DP-700 content of a live Microsoft Fabric data engineering program, where Fabric workspaces sync to Git repos directly. To test the water first, the free webinars include a live repo walkthrough.
What Changed in Git Between 2.51 and 2.55
git history, added in 2.54, is the interesting one. git history reword rewrites a commit message in place and updates every branch descending from it without touching your working tree, and GitHub's release notes point out it even works in a bare repository. git history split carves one commit into two by picking hunks, and 2.55 added git history fixup. All three replace an interactive rebase done carefully. All three are still experimental.
git repo info, from 2.52, answers questions about the repository itself in a script-friendly format:
$ git repo info layout.bare object.format references.format
layout.bare=false
object.format=sha1
references.format=reftable
Performance. Git 2.55, released in June 2026, brought incremental multi-pack index support to git repack, the release highlights citing one bitmap generation benchmark dropping from 612 seconds to 294. It also made the filesystem monitor work on Linux, which matters once git status has become a coffee break.
The case study: how Git learned to handle 3.5 million files
When Microsoft moved the Windows codebase to Git in 2017 the repository held 3.5 million files and a full clone ran past 300GB, according to GitHub's write-up of the Scalar project. Plain Git could not do it. The first answer was a virtual filesystem layer, but the team pushed the fixes upstream instead: cone-mode sparse-checkout, which checks out a subset of directories cheaply, and the filesystem monitor, which stops Git stat-ing millions of files per command. That got git status to three or four seconds on a repo that size.
Every one of those features is in the Git on your laptop. git clone --filter=blob:none, git sparse-checkout set and git maintenance start are the consumer-grade versions, and on a large monorepo they cut a twenty-minute clone to two.
Model and data repos hit the same wall for different reasons, which is why versioning strategy comes up in the AI-300 material behind 360DT's MLOps Engineer course and in agent project structure on the AI Engineer course. Anyone working alongside Claude Code in a repository, the pattern covered in the CCDV-F prep course, meets it sooner, because an agent that can commit is an agent whose mistakes you need the reflog to undo.
Also read: Linux Commands Cheat Sheet for DevOps in 2026: 50 Commands With Worked Examples, the companion reference for the shell you run all of this in.
What I Would Actually Do This Week
Take the three config lines above: pull.rebase true, init.defaultBranch main, and the pushf alias that makes --force-with-lease the only force push you ever type. Thirty seconds of setup removes the two commonest ways teams lose work.
Then pick the worst repository you work in, the one where git status takes four seconds, and run git maintenance start in it. Finally, spend twenty minutes deliberately breaking a throwaway repo: commit something, reset it, delete the branch, recover all of it from the reflog. Doing that once while nothing is at stake beats reading this page five times, because people panic on Friday evening not for want of knowing git reflog exists but because they have never run it. When you want the pipeline layer on top, the AWS Solutions Architect and DevOps course is the direct next step, or sit in on a free webinar and watch the workflow run live before you pay for anything.
Related guides
- Docker Best Practices in 2026: 10 Mistakes That Bloat Your Images because .dockerignore mistakes are cousins of the .gitignore ones here.
- SAA-C03 vs DOP-C02: Which AWS Certification Should You Take First? for where the DevOps track starts once Git is second nature.
- System Administrator to DevOps Engineer in India 2026 if version control is what you are adding on top of an ops background.
- DevOps Engineer Salary in India 2026 for what this whole toolchain is worth in advertised pay bands.
- What Is Spec-Driven Development in 2026? on how commit hygiene changes when an agent writes most of the diff.
Frequently asked questions
What are the most important Git commands to learn first?
Eight cover the daily loop: git clone, git status -sb, git add -p, git commit, git switch -c, git pull --rebase, git push -u origin and git reflog. Learn those before touching rebase or bisect. The rest of this Git commands cheat sheet is lookup material.
How do I undo a Git commit that I have already pushed?
Use git revert <sha>, which creates a new commit undoing the changes. Do not use git reset on a branch other people have pulled, because it rewrites history that already exists on their machines. Reset is for local commits; revert is for anything shared.
What is the difference between git switch and git checkout?
git checkout does two unrelated jobs: moving between branches and restoring files. Git 2.23 split those into git switch and git restore, and Git 2.51 removed the experimental label from both. Checkout still works and is not being removed, but switch and restore are clearer.
How do I recover a deleted branch in Git?
Run git reflog, find the last commit SHA the branch pointed at, then run git switch -c <branch-name> <sha>. The git-reflog documentation defaults unreachable entries to 30 days and reachable ones to 90, so recovery works for weeks after deletion.
What does git push force-with-lease do that force does not?
--force overwrites the remote branch unconditionally, including commits someone pushed while you were working. --force-with-lease first checks the remote is still at the commit your last fetch saw, and refuses the push if not. It costs nothing and prevents the most destructive Git accident.
How do I make Git faster on a large repository?
Three things: clone with --filter=blob:none so file contents download on demand, run git maintenance start so commit-graph and prefetch run hourly in the background, and use git sparse-checkout set to limit which directories are populated. Those are the techniques that got Git working on a 3.5 million file repository.
What is new in Git in 2026?
Git 2.52 added the experimental git last-modified and git repo info commands plus a geometric maintenance strategy. Git 2.54 added experimental git history reword and git history split with config-based hooks. Git 2.55, from June 2026, brought the filesystem monitor to Linux and now requires Rust to build by default.
Is a Git commands cheat sheet enough to learn Git?
No, and that is worth saying plainly. A cheat sheet tells you which command to type; it cannot give you the mental model of the four areas that explains why that command works. Read the diagram section once, then use the tables as reference. Twenty minutes of deliberately breaking and recovering a throwaway repo teaches more than any list.
About this guide. 360 Digital Transformation is an Authorized Training Partner of Anthropic and Microsoft. Other certification bodies, vendors and employers named here are not affiliated with us. Tools and versions change quickly; commands and figures cited were checked on 28 September 2026.




