Home › Developer Tools › Git Cheat Sheet

Git Cheat Sheet

Find the right Git command by what you want to do, copy it in one click, and let the fix-it wizard write the exact steps for common rescues like undoing a commit, renaming a branch or squashing commits.

Last updated:

Advertisement
Advertisement

How to use the Git Cheat Sheet

  1. Search or browse: type what you want to do (undo, rename, stash, tag) or pick a category tab.
  2. Copy a command with the Copy button and replace the highlighted placeholders such as <branch> with your own values.
  3. Use the fix-it wizard when you are in a specific situation: choose it from the list, answer the questions and fill in your names.
  4. Follow the generated steps in order. Copy them one at a time or all at once, and read any warning before running a command marked as dangerous.
  5. Download the cheat sheet as a Markdown file to keep it next to your project.

git reset vs git revert vs git restore

These three commands all "undo" something, which is why they are easy to mix up. The key question is whether the commit has already been shared.

CommandWhat it changesRewrites history?Use it when
git restore <file>Working files (or the staging area with --staged)NoYou want to throw away or unstage edits that are not committed yet
git reset --soft HEAD~1Moves the branch back; changes stay stagedYesThe last commit is local and you want to redo it
git reset HEAD~1 (mixed)Moves the branch back; changes stay in your files, unstagedYesYou want to split or re-stage the work of a local commit
git reset --hard HEAD~1Moves the branch back and deletes the changesYesYou want the commit and its work gone (recoverable only through reflog)
git revert <commit>Adds a new commit with the opposite changesNoThe commit is already pushed to a branch other people use

How Git moves your changes

Git keeps your work in four places. Most commands move changes from one place to the next:

  1. Working directory: the files you edit. git restore discards changes here.
  2. Staging area (index): what will go into the next commit. git add moves changes in, git restore --staged moves them out.
  3. Local repository: your commits. git commit records the staged snapshot; git reset moves the branch pointer back.
  4. Remote repository: the shared copy, such as GitHub or GitLab. git push uploads commits, git fetch downloads them and git pull downloads and merges.

Reading HEAD~ and HEAD^ references

ReferenceMeans
HEADThe commit you currently have checked out
HEAD~1 or HEAD~The parent of HEAD (one commit back)
HEAD~3Three commits back, following first parents
HEAD^2The second parent of a merge commit (the branch that was merged in)
main..featureCommits on feature that are not on main
origin/mainYour last-fetched copy of main on the remote called origin
@{u}The upstream branch of the current branch
stash@{0}The most recent stash entry

A short rule that prevents most Git disasters: rewrite history (reset, commit --amend, rebase) only on commits that exist nowhere but your computer or your own branch, and use git revert for anything others may already have pulled.

Frequently asked questions

How do I undo the last commit in Git?

If you have not pushed it, run git reset --soft HEAD~1 to remove the commit but keep its changes staged, or git reset HEAD~1 to keep them unstaged. If the commit is already pushed to a shared branch, run git revert HEAD instead, which adds a new commit that reverses it without rewriting history.

What is the difference between git reset and git revert?

git reset moves the branch pointer back, removing commits from the branch history, so it should only be used on commits nobody else has. git revert creates a new commit that applies the opposite changes, so history is preserved and it is safe on pushed, shared branches.

How do I rename a Git branch locally and on the remote?

Rename it locally with git branch -m old-name new-name, push the new name with git push origin -u new-name, then delete the old remote branch with git push origin --delete old-name. Teammates should then run git fetch --prune and switch to the new branch.

What is the difference between git fetch and git pull?

git fetch downloads new commits and branches from the remote but does not change your working files. git pull runs a fetch and then merges (or rebases, with --rebase) the remote branch into your current branch.

Is git push --force dangerous?

It overwrites the remote branch with your local one, which can delete commits other people pushed. Prefer git push --force-with-lease, which refuses to overwrite the remote if it has commits you have not fetched, and never force push to a shared main branch.

Should I use git switch or git checkout?

Both work. git switch (for branches) and git restore (for files) were added in Git 2.23 to split the many jobs of git checkout into clearer commands. git checkout still works in every version, so older tutorials and scripts use it.

Can I recover a branch or commit I deleted?

Usually yes. Run git reflog to see where HEAD has pointed recently, find the commit hash from before the deletion, then run git branch recovered-name <hash>. Reflog entries are kept for 90 days by default, so act before garbage collection removes them.

Are all the tools on FreeToolCabin tested for quality and accuracy?

Yes! Every tool on our site undergoes automated Q/A testing in real browser environments to ensure high precision, correct output, and zero errors. If you happen to spot a bug or have a suggestion, please contact us at [email protected] and our team will review it right away.

Related tools

Linux Commands Cheat SheetSearchable Linux and bash command reference with flags explained, examples and copy buttons.Gitignore GeneratorBuild a .gitignore from 50+ templates for languages, frameworks, IDEs and OS, merged and deduped.Markdown Cheat SheetInteractive Markdown syntax reference: edit every example and see the live rendered preview.Regex Cheat Sheet75+ ready-to-use regex patterns for emails, URLs, IPs and dates, each with a live test box.Dockerignore GeneratorBuild a .dockerignore from Node, Python, Go and Java templates, plus your own entries.GitHub Actions Workflow GeneratorBuild a GitHub Actions CI workflow: triggers, matrix, caching, tests, Pages or Docker deploy.GitLab CI Config GeneratorGenerate a .gitlab-ci.yml with stages, jobs, images, cache, artifacts and rules from templates.tsconfig.json GeneratorBuild a tsconfig.json with target, module, strict checks and path aliases, each option explained.Online Python CompilerRun Python 3 in your browser with input(), numpy, pandas, charts and share links.JSON EditorEdit JSON in a tree and as code side by side: add, rename, drag, change types, undo and download.Unzip FilesOpen and extract ZIP files online.RAR & 7z ExtractorOpen RAR, 7z and other archives online and extract files.Regex TesterTest and debug regular expressions live.File Info ViewerCheck file size, type, date and MD5/SHA hashes.SQLite ViewerOpen .db and .sqlite files in your browser, browse tables and run SQL queries.DOCX ViewerOpen and read Word .docx files in your browser, then print or save them as HTML.EPUB ReaderOpen and read EPUB e-books in your browser with pages, a table of contents and font controls.What Is My BrowserSee your browser, version, OS, engine, screen and which web features it supports.Font ViewerPreview TTF, OTF, WOFF and WOFF2 fonts with sample text, waterfall, glyphs and metadata.Markdown EditorWrite Markdown with a toolbar, live split preview, autosave and .md or HTML export.JavaScript Keycode FinderPress any key to see its JavaScript key, code, keyCode, which, location and modifiers.QR Code ScannerScan QR codes with your camera or from an image and safely read the link or text.RAID CalculatorUsable capacity, efficiency and fault tolerance for RAID 0, 1, 5, 6, 10, 50 and 60 arrays.JSONPath TesterTest JSONPath expressions live: filters, slices, wildcards and recursive search, with matches highlighted.Mermaid Diagram EditorWrite Mermaid code and see flowcharts, sequence, Gantt and ER diagrams live. Export SVG or PNG.Country Codes ListSearch ISO 3166 alpha-2, alpha-3 and numeric country codes with calling codes and TLDs.CSS Selector TesterTest CSS selectors on your HTML: highlighted matches, match count and specificity.HAR File ViewerOpen a .har file to see a waterfall timeline, headers, bodies, timings and size totals.jq PlaygroundRun jq filters on JSON in your browser with live output, flags and an example library.Regex ExplainerPaste a regular expression and get a plain-English breakdown, railroad diagram and flag notes.XPath TesterTest XPath expressions on XML or HTML: highlighted matches, node paths, values and examples.EML File ViewerOpen .eml email files to read the message, headers and raw source and save attachments.Graphviz Online ViewerWrite Graphviz DOT code and render graphs live; switch layout engines, export SVG or PNG.JavaScript Online CompilerWrite and run JavaScript in your browser with a console, timing, error lines and share links.Jupyter Notebook ViewerOpen .ipynb files and read code, Markdown, math, tables, plots and errors without Python.LaTeX Table GeneratorEdit a table like a spreadsheet or paste from Excel and get LaTeX tabular or booktabs code.Log File ViewerOpen huge log files with level colors, regex and time filters, JSON pretty-print and tail -f.Logic Gate SimulatorBuild logic circuits with AND, OR, NOT, XOR gates and flip-flops; see live outputs and truth tables.JMESPath TesterEvaluate JMESPath expressions against JSON live, the query language used by the AWS CLI.MongoDB Query TesterTest MongoDB find filters, projections and aggregation pipelines on sample JSON documents.Semantic Version CalculatorBump, compare, sort and test SemVer versions against npm ^, ~ and x ranges.XSLT TesterRun an XSLT 1.0 stylesheet on XML in your browser and see the output as HTML, XML or text.ASCII Diagram EditorDraw boxes, arrows and text on a character grid and copy plain-text diagrams for code and READMEs.DBF File ViewerOpen dBase .dbf files and shapefile tables, search and sort records, export CSV or XLSX.MBOX File ViewerOpen .mbox mail archives: list and search messages, read them, save attachments, export EML.MDB File ViewerOpen Access .mdb and .accdb databases in your browser: list tables, view rows, export CSV.Shapefile ViewerView zipped shapefiles on a map with the attribute table, then export to GeoJSON or CSV.MSG File ViewerOpen Outlook .msg emails in your browser: sender, recipients, body, headers and attachments.Online Code EditorVS Code-style editor in your browser: tabs, 50+ languages, find/replace, autosave.Online Hex EditorOpen any file as hex and ASCII, edit bytes, search, inspect values and save the result.PHP Online CompilerRun PHP 8 code in your browser with output, HTML preview, error lines and share links.PlantUML EditorWrite PlantUML and see sequence, class, activity and more diagrams live. Export SVG or PNG.Sorting Algorithm VisualizerWatch bubble, insertion, merge, quick, heap and radix sort step by step with live counters.Lottie ViewerOpen Lottie JSON or .lottie files to play, pause, scrub frames, change speed and see details.Diff ViewerPaste a git diff or .patch file and view it side by side or inline, with file navigation.EditorConfig GeneratorBuild an .editorconfig with indent, charset, line endings and trim rules per file pattern.Folder Compare ToolCompare two folders by file list, size and SHA-256 hash, then open a text diff of changed files.Glob Pattern TesterTest glob patterns like **/*.js, {a,b} and !exclusions against a list of file paths.
See all 53 Code Playgrounds & Testers →