Git Commands Cheatsheet
Complete, copy-ready reference for daily Git workflows. Instant commands for branching, merging, rebasing, stashing, undoing mistakes, and disaster recovery via reflog.
Configuration & Identity
git config --global user.name "Your Name"Sets your global author name for all commit logs across workstation.
Pro Tip: Run once per workstation setup.
git config --global user.email "you@example.com"Sets your global commit author email (must match GitHub/GitLab).
Pro Tip: Essential for commit attribution.
git config --global init.defaultBranch mainSets "main" as the default initial branch name for all new repositories.
Pro Tip: Modern standard replacing legacy "master".
git config --global core.editor "code --wait"Configures VS Code as your default editor for interactive rebase and commit messages.
Pro Tip: Add --wait so Git pauses until file is saved.
git config --list --show-originDisplays all active Git configuration variables along with their origin file paths.
Pro Tip: Great for debugging config conflicts.
Repository Setup & Initialization
git initInitializes a new, empty Git repository in the current working directory.
Pro Tip: Creates the hidden .git directory.
git clone https://github.com/user/repo.gitClones an entire remote repository including commit history and branches.
Pro Tip: Creates a local directory named repo.
git clone --depth 1 https://github.com/user/repo.gitPerforms a shallow clone containing only the latest commit snapshot.
Pro Tip: Dramatically reduces download size in CI/CD pipelines.
git clone -b develop https://github.com/user/repo.gitClones repository and immediately checks out the specified branch.
Pro Tip: Avoids needing manual checkout post-clone.
Staging & Committing (Basic Workflow)
git status -sShows the working tree status in a concise, compact format (M, ??, A).
Pro Tip: Red indicates unstaged, green indicates staged.
git add .Stages all new, modified, and deleted files in the entire project for commit.
Pro Tip: Use with care; inspect git status first.
git add -p file.jsInteractively stages individual chunks (hunks) of changes within a file.
Pro Tip: Best practice for splitting multi-purpose edits into atomic commits.
git commit -m "feat: implement user auth"Records staged changes into a new immutable commit with an inline message.
Pro Tip: Follow Conventional Commits standard.
git commit --amend --no-editAppends staged changes to the most recent commit without modifying its message.
Pro Tip: Only use before pushing to remote!
git diffDisplays line-by-line differences between unstaged modifications and the index.
Pro Tip: Shows what you have not yet staged.
git diff --stagedShows differences between staged files and the most recent commit.
Pro Tip: Confirms exactly what will enter next commit.
Branching & Switching
git branchLists all local branches, highlighting the currently active branch with an asterisk.
Pro Tip: Add -a to include remote tracking branches.
git switch -c feature/loginCreates a new branch named feature/login and switches to it immediately.
Pro Tip: Modern replacement for legacy git checkout -b.
git switch mainSwitches the working directory to the existing branch named main.
Pro Tip: Safer than checkout because it prevents file overwrite confusion.
git branch -d feature/loginSafely deletes a local branch only if it has already been merged into upstream.
Pro Tip: Use -D (capitalized) to force delete unmerged branches.
git branch -m old-name new-nameRenames a local Git branch.
Pro Tip: Rename active branch with git branch -m new-name.
Merging & Rebasing
git merge feature-branchMerges changes from feature-branch into the current active branch.
Pro Tip: Creates a merge commit unless fast-forward is possible.
git merge --no-ff feature-branchForces a dedicated merge commit even if a fast-forward merge was possible.
Pro Tip: Preserves the historical boundary of a feature branch.
git rebase mainReplays commits from your current branch onto the tip of main for a linear history.
Pro Tip: Golden rule: Never rebase public shared branches.
git rebase -i HEAD~3Opens an interactive rebase editor for the last 3 commits to squash, edit, or reorder.
Pro Tip: Change pick to squash (s) to combine commits.
git rebase --abortCompletely cancels an ongoing rebase operation and restores previous HEAD state.
Pro Tip: Use when merge conflicts become unmanageable.
Stashing Temporary Work
git stash -uTemporarily shelve all modified and untracked files without committing.
Pro Tip: Cleans working tree so you can switch branches.
git stash popApplies the most recently stashed changes and deletes them from the stash list.
Pro Tip: Restores shelved work to working directory.
git stash listDisplays all stored stashes with their stash@{n} index identifiers.
Pro Tip: Shows stash timestamp and branch origin.
git stash drop stash@{0}Permanently removes a specific stash entry from storage.
Pro Tip: Use git stash clear to wipe all stored stashes.
Undoing Mistakes & History Recovery
git restore file.jsDiscards unstaged changes in a file, restoring it to the last committed state.
Pro Tip: Irreversible! Uncommitted modifications are lost.
git restore --staged file.jsUnstages a file while keeping your modifications intact in the working directory.
Pro Tip: Replaces legacy git reset HEAD file.
git reset --soft HEAD~1Undoes the most recent commit, keeping all changed files staged in the index.
Pro Tip: Perfect for re-committing with a better message.
git reset --hard HEAD~1Destructively obliterates the last commit and discards all changed files.
Pro Tip: Extremely dangerous: uncommitted work is destroyed.
git revert <commit-hash>Creates a new commit that records the exact inverse of the targeted commit.
Pro Tip: Safe for shared public branches because it preserves history.
git reflogShows a chronologically ordered log of every HEAD pointer movement.
Pro Tip: The ultimate safety net: lets you recover lost commits and deleted branches.
Remote Repositories & Collaboration
git remote -vLists all configured remote repository nicknames (e.g. origin) and their fetch/push URLs.
Pro Tip: Confirms remote endpoint targets.
git fetch originDownloads all new branches and commits from origin without merging into local files.
Pro Tip: Safe way to inspect remote changes without altering your workspace.
git pull --rebase origin mainFetches remote commits and rebases your local commits on top of them.
Pro Tip: Prevents unnecessary "Merge branch" clutter commits.
git push -u origin feature-branchPushes the local branch to the remote repository and sets upstream tracking.
Pro Tip: Subsequent pushes only require git push.
git push origin --delete branch-nameDeletes a branch on the remote server (e.g. GitHub/GitLab).
Pro Tip: Removes merged feature branches on remote.
Understanding Git Internals: Blobs, Trees, and the Directed Acyclic Graph
Unlike centralized version control systems (such as SVN or CVS) that track delta file differences, Git stores data as a series of complete repository snapshots over time. Every time you run git commit, Git takes a snapshot of what all your files look like at that exact moment and stores a reference to that snapshot.
Internally, Git manages four foundational object types inside the .git/objects/ directory:
- Blobs (Binary Large Objects): Stores the compressed raw byte content of files without filenames or permission modes.
- Trees: Equivalent to filesystem directories; maps human-readable filenames and execution permissions to their corresponding blob SHA-1 hashes.
- Commits: A metadata envelope containing a pointer to a root tree object, parent commit hashes, author timestamps, and the commit message.
- Tags: Permanent annotated references pointing directly to specific commit SHA identifiers.
The Three Trees of Git Architecture
When working in Git, code transitions through three distinct logical zones:
| Zone | Description | Associated Commands |
|---|---|---|
| Working Directory | Actual physical files on your local hard drive that you edit in your IDE. | git restore file.js (discards edits) |
| Staging Area (Index) | Binary index file tracking exactly what changes will enter the next commit snapshot. | git add ., git restore --staged |
| Git Repository (HEAD) | Permanent, cryptographically hashed immutable database of commits. | git commit, git reset, git log |
Frequently Asked Questions (FAQs)
What is the difference between git restore, git revert, and git reset?
git restore alters files in the working directory or staging index without changing commit history. git reset moves the current branch HEAD backward in time (soft keeps files staged, hard discards all changes). git revert creates a brand-new commit that applies the exact inverse diff of an older commit, making it the only safe way to undo mistakes on public, shared branches.
Why should I use git switch and git restore instead of git checkout?
In Git 2.23+, the multi-purpose git checkout command was split into two focused commands: git switch (specifically for managing and switching branches) and git restore (specifically for discarding or unstaging file modifications). This separation eliminates accidental file overwrites when switching branches.
How does git reflog recover lost or accidentally deleted commits?
Git never deletes commits immediately. Whenever HEAD changes (via commit, checkout, rebase, or reset), Git writes an entry to the local reflog. Even after running git reset --hard or deleting a branch, running git reflog will reveal the commit SHA-1 before the operation. You can recover it instantly with git branch recovered-branch <SHA-1>.
When should I use git rebase vs git merge?
Use git rebase when incorporating upstream updates from main into your private feature branch to maintain a clean, linear project history. Use git merge when integrating a completed feature branch back into main or production branches to preserve the full collaborative timeline.
Explore Related Tools
Hand-picked utilities and calculators related to this tool.