1. Home
  2. Blog
  3. Software Development

Software Development

Git Commands Cheat Sheet: The Commands You Actually Use, With Examples

A practical Git reference grouped by what you are trying to do, from your first commit to undoing a mistake. Keep it open while you work, and use the undo guide before you reach for anything risky.

8 min read
Git commands cheat sheet: the commands you actually use, with examples

Key takeaways

  • A change moves through three areas: working directory, staging area and repository.
  • git status is the safest command you have, so run it constantly.
  • Use git revert to undo shared commits, and keep git reset --hard for local work you are sure about.
  • git reflog can usually rescue commits you thought were lost.

Nobody remembers every Git command, and you do not need to. This Git commands cheat sheet focuses on the small set that covers nearly all daily work, grouped by the job you are trying to do.

We tested the local commands in a throwaway demo repository using Git for Windows, and the output shown comes from that run, with line-ending warnings removed. Your commit hashes will differ. The remote commands need a server, so we did not run those. New to version control? Start with our Git tutorial for beginners.

How Git thinks: three areas

Most confusion disappears once you know where a change lives:

Area What it holds Moved there by
Working directory Your files as you edit them Editing
Staging area (index) Changes selected for the next commit git add
Local repository Your saved commit history git commit
Remote repository The shared copy, such as on GitHub git push

Setup and starting a project

Command What it does
git config --global user.name "Asha" Sets your name on commits
git config --global user.email "a@b.com" Sets your email on commits
git config --global init.defaultBranch main Names new default branches main
git init Creates a repository in the current folder
git clone <url> Downloads an existing repository
git config --list Shows your current settings

Save your work

Command What it does
git status Shows what has changed
git add file.txt Stages one file
git add . Stages all changes in this folder
git add -p Stages selected parts of a file
git diff Shows unstaged changes
git diff --staged Shows what will be committed
git commit -m "Message" Saves staged changes as a commit
git commit -am "Message" Stages tracked files and commits them

Here is how the short status view changes as a new file moves along:

$ echo "hello" > app.txt
$ git status --short
?? app.txt

$ git add app.txt
$ git status --short
A  app.txt

$ git commit -m "Add app file"

?? means untracked, and A means added to staging. In the two-column format, the left column is the staging area and the right column is your working directory. Note that git commit -am skips brand new files, so you must add those explicitly first.

Branches

Command What it does
git branch Lists local branches
git branch -a Includes remote branches
git switch feature/login Moves to a branch
git switch -c feature/login Creates a branch and moves to it
git merge feature/login Merges that branch into the current one
git rebase main Replays your commits on top of main
git branch -d feature/login Deletes a merged branch
git branch -D feature/login Force deletes an unmerged branch

Here is a small feature branch from start to finish:

$ git switch -c feature/login
$ echo "login" >> app.txt
$ git commit -am "Add login"
$ git switch main
$ git merge --no-edit feature/login
$ git log --oneline --graph
* d0450b6 Add login
* 676b684 Add app file

$ git branch -d feature/login
Deleted branch feature/login (was d0450b6).

The history is a straight line because main had not moved, so Git did a fast-forward merge. You will still see git checkout in older guides. It works, but the newer switch and restore commands split its many jobs into clearer ones. To choose between merging and rebasing, read Git merge vs rebase.

Working with remotes

Command What it does
git remote -v Lists remotes and their URLs
git remote add origin <url> Connects a remote
git fetch Downloads changes without merging
git pull Fetches, then integrates into your branch
git push Uploads your commits
git push -u origin feature/login Pushes a new branch and tracks it
git push origin --delete feature/login Deletes a remote branch
git push --force-with-lease Force pushes, but only if nobody else has pushed

fetch is always safe, because it never changes your files. If you need to overwrite a branch after a rebase, prefer --force-with-lease to plain --force, as it refuses to wipe out a colleague’s new commits.

Stash: set work aside

Stash is useful when you need to switch tasks but are not ready to commit:

$ echo "wip" >> app.txt
$ git stash
$ git status --short
                       # clean, the change is put away
$ git stash pop
$ git status --short
 M app.txt
Command What it does
git stash Saves changes and cleans your working directory
git stash -u Includes untracked files
git stash list Shows saved stashes
git stash pop Restores the latest stash and removes it
git stash apply Restores it but keeps it saved

View history

Command What it does
git log --oneline Shows one line per commit
git log --oneline --graph --all Draws all branches
git log -p file.txt Shows a file’s changes over time
git show <hash> Shows one commit in detail
git blame file.txt Shows who last changed each line
git reflog Shows everywhere HEAD has been
git bisect Binary searches for the commit that added a bug

Undo mistakes: “I want to…”

This is the part most people look up. Find your situation:

Situation Command
Discard unstaged edits in a file git restore file.txt
Unstage a file but keep the edits git restore --staged file.txt
Fix the last commit’s message or files git commit --amend
Undo the last commit, keeping changes staged git reset --soft HEAD~1
Undo the last commit, keeping changes unstaged git reset HEAD~1
Undo a pushed commit safely git revert <hash>
Throw away all local changes git reset --hard
Remove untracked files git clean -fd (preview with -n)
Recover a “lost” commit git reflog, then git branch rescue <hash>

Tip: Before anything risky, run git branch backup. It costs nothing and gives you a label to return to. git reset --hard and git clean can permanently destroy uncommitted work, which even reflog cannot recover.

Reset vs revert vs restore

These three names cause much confusion, but they do quite different things:

Command Acts on Changes history? Safe on shared branches?
git restore Files No Yes, but it discards local edits
git revert A commit, by adding its opposite Adds to it Yes
git reset The branch pointer Rewrites it No

In our demo, we committed a bad line and reverted it. The file went back to its earlier content, while the mistake stayed visible in the log as history:

$ echo "oops" >> app.txt
$ git commit -am "Bad change"
$ git revert --no-edit HEAD
$ cat app.txt
hello
login

Then git reset --soft HEAD~1 removed that last commit but kept its changes staged, which git status --short showed as M app.txt.

Tags

Command What it does
git tag Lists tags
git tag v1.0 Creates a lightweight tag
git tag -a v1.0 -m "Release" Creates an annotated tag, best for releases
git push origin v1.0 Pushes a tag (tags do not push by default)

Tags often trigger release pipelines, as our GitHub Actions CI/CD guide explains.

A simple daily workflow

git switch main
git pull
git switch -c feature/search
# edit files
git status
git add -p
git commit -m "Add search by product name"
git push -u origin feature/search
# open a pull request, get a review, then merge

Write commit messages that explain the change in the imperative, like “Fix login redirect”. You will thank yourself when reading the log six months from now.

Common mistakes

  • Committing secrets. Removing a file in a later commit does not remove it from history. Rotate the secret immediately, and use .gitignore.
  • Rewriting shared history. Do not reset or rebase commits that others have already pulled.
  • Using git add . blindly. Check git status first, so build files and logs stay out.
  • Using plain --force. Prefer --force-with-lease.
  • Making huge commits. Small ones are easier to review, revert and bisect.

Final thoughts

Learn the three areas and a dozen commands, and Git stops being scary. Keep the undo table handy and remember that git status and git reflog are your safety net. To build confidence, create a throwaway repository, and deliberately break and repair it, since that is the cheapest place to make mistakes.

Frequently asked questions

What are the most used Git commands?

The everyday set is git status, add, commit, push, pull, switch, branch, merge and log. Those few commands cover most of a typical working day.

How do I undo my last commit in Git?

If it is local, use git reset –soft HEAD~1 to keep the changes staged. If you have already pushed it, use git revert so that history stays intact for others.

What is the difference between git fetch and git pull?

git fetch only downloads new data and leaves your files alone. git pull fetches and then merges or rebases those changes into your current branch.

What is the difference between git reset and git revert?

git reset moves the branch pointer and can rewrite history. git revert adds a new commit that undoes an earlier one, which makes it safe on shared branches.

Can I recover a deleted branch in Git?

Usually, yes. Find its last commit with git reflog, then recreate the branch with git branch name followed by the hash, provided Git has not yet cleaned it up.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →