Git Commands Cheat Sheet — 50 Commands + Real-World Examples

Last updated: 2026-06-08 · Category: Developer Tools · Reading time: 12 min

✍️ Author:DevToolbox Team📅 Updated:2026-06-24📎 References:RFC Standards

📌 Key Takeaways

  • Git Commands Cheat Sheet — 50 Commands + Real-Worl is widely used by developers
  • Based on RFC standards and real-world experience
  • Free online tools, runs locally, no data upload
  • FAQ section at the bottom answers common questions
✍️ Author:DevToolbox Team📅 Updated:2026-06-24📎 References:RFC Standards

📌 Key Takeaways

  • Git Commands Cheat Sheet — 50 Commands + Real-Worl is widely used by developers
  • Based on RFC standards and real-world experience
  • Free online tools, runs locally, no data upload
  • FAQ section at the bottom answers common questions

This Git command cheat sheet organizes the Git commands you'll use in 90% of daily developer scenarios into 6 workflow categories: Setup & Initialization, Daily Workflow (add / commit / push), Branch Management, Undo & Rollback (git reset / git revert), Remote Repositories, and Advanced & Troubleshooting (git rebase / git reflog). Each command is paired with ready-to-copy real-world code snippets and scenario explanations, plus 5 frequently asked Git FAQ at the end. Whether you're a beginner learning version control or a senior developer wanting to review Git workflows systematically, you can find the answer in 3 minutes.

1. Setup & Initialization

The very first thing to do after installing Git is to configure your user info — every commit will carry these two fields. Configuration comes in two flavors: --global (stored in ~/.gitconfig) and current-repo only (no --global, stored in .git/config). It's recommended to set your name and email globally, with per-project overrides as needed. These 5 commands are an unavoidable part of any Git tutorial and the first step into version control.

1.1 Set User Name and Email

git config --global user.name "Your Name"
git config --global user.email "[email protected]"
git config --global init.defaultBranch main

Adding --global applies to all repositories for the current user; without it, the setting applies only to the current repository (overriding the global value). init.defaultBranch main makes git init use main instead of the old master as the default branch, staying consistent with GitHub.

1.2 Initialize & Clone

git init                          # Turn the current directory into a Git repo
git init my-project               # Create and initialize a new my-project directory
git clone https://github.com/user/repo.git
git clone [email protected]:user/repo.git   # SSH protocol
git clone --depth 1 <url>          # Shallow clone (only the latest commit, saves time)

git clone automatically adds a remote repository alias named origin and checks out the remote main branch locally.

1.3 Set Up Common Aliases (Highly Recommended)

git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage 'reset HEAD --'
git config --global alias.lg "log --oneline --graph --decorate -20"

After setup, git co is equivalent to git checkout, git st equals git status. Over time, this saves a tremendous amount of typing. See FAQ for details.

1.4 Windows Line Ending Issues (Must Read)

# Recommended for macOS / Linux
git config --global core.autocrlf input

# Recommended for Windows
git config --global core.autocrlf true

# One-time fix for an already polluted repo
git rm --cached -r .
git reset --hard

Windows defaults to CRLF, Linux/macOS defaults to LF — cross-platform collaboration can trigger whole-file "modifications". core.autocrlf controls whether Git automatically converts line endings on checkout / commit.

1.5 Configure SSH Key for Pushing to GitHub

ssh-keygen -t ed25519 -C "[email protected]"   # Generate key pair
cat ~/.ssh/id_ed25519.pub                     # Copy public key to GitHub Settings → SSH and GPG keys
ssh -T [email protected]                         # Test connection, "Hi xxx!" means success

Once SSH is set up, all git push / git pull operations skip the password prompt — more convenient than HTTPS.

2. Daily Workflow (Core)

This is the core loop of any Git workflow: edit code → git add to stage → git commitgit push it up. A commit passes through 3 areas from "Working Directory" to "Local Repository" to "Remote Repository": Working Directory, Staging Area (Index), and Repository. The most common confusion for beginners is these 3 areas — memorizing the diagram below covers 80% of Git commands scenarios.

          git add            git commit
Working Dir ───────▶ Staging ────────▶ Local Repo
   ▲                    │                    │
   │                    │                    │
   └──── git checkout ───┘                    │
   └───────────── git reset ─────────────────┘
                                            │
                                            │ git push
                                            ▼
                                         Remote Repo

2.1 Check Status & Changes

git status                       # View modified / staged / untracked files
git status -s                    # Compact output ?? / M / A / D etc.
git diff                         # Working dir vs staging area (un-added changes)
git diff --staged                # Staging area vs latest commit (added but not committed)
git diff HEAD                    # Working dir vs latest commit (all uncommitted changes)
git log --oneline --graph -20    # Pretty commit history (with branch graph)
git log --stat                   # Which files each commit changed
git log -p file.txt              # Modification history for a specific file
git blame file.txt                # Show who changed each line and in which commit

2.2 Stage & Commit

git add file.txt                 # Stage a single file
git add src/                     # Stage a whole directory
git add .                        # Stage all changes (including new files)
git add -p                       # Interactive staging (hunk-level, good for large changes)
git commit -m "feat: add login page"          # Commit with a message
git commit -am "fix: typo"      # Skip add, commit modifications to tracked files directly
git commit --amend               # Merge this commit into the previous one (edit message / add files)

Recommended commit message format: <type>: <subject>, where common types are feat / fix / docs / refactor / test / chore. Paired with git commit -m, you can convey intent in one line — six months later, looking at git log won't leave you puzzled.

2.3 Stash Working Changes (Life-Saver with git stash)

git stash                        # "Pack up" current uncommitted changes and set aside
git stash push -m "WIP: login"  # Add a comment for easy identification later
git stash list                   # View all stashes
git stash pop                    # Restore the most recent stash and remove its record
git stash apply stash@{2}        # Restore a specific stash but keep the record
git stash drop stash@{0}         # Delete a specific stash
git stash clear                  # Remove all stashes

Classic scenario: you're halfway through changes on feature/login, and an urgent bug hits main on production — first git stashgit checkout main → fix it → git checkout feature/logingit stash pop.

2.4 Sync with Remote

git pull                         # = git fetch + git merge, "fetch and merge"
git pull --rebase                # = git fetch + git rebase, clean linear history
git push                         # Push to default remote + default branch
git push origin feature/login    # Push to a specific branch
git push -u origin main          # -u sets upstream; afterwards just git push / git pull

2.5 fetch vs pull vs merge vs rebase

git fetch origin                 # Only download remote commits, doesn't touch local branches
git fetch --all --prune          # Fetch all remotes, prune deletes refs to deleted remote branches

git merge origin/main            # Merge origin/main into the current branch
git rebase origin/main           # "Replay" the current branch on top of origin/main

git fetch only updates remote-tracking branches and does not modify your local code; git pull = fetch + merge. When multiple people collaborate on the same branch, git pull --rebase is recommended to avoid unnecessary merge commits.

2.6 Real-World: Complete Commit Workflow

# 1. Pull latest
git checkout main && git pull --rebase

# 2. Create feature branch
git checkout -b feature/login

# 3. Edit code...
# 4. Check changes
git status
git diff

# 5. Stage + commit
git add src/login.ts
git commit -m "feat(login): add email + password form"

# 6. Push and open PR
git push -u origin feature/login

3. Branch Management

Git branch management offers the best ROI among all Git commands — lightweight, cheap, and encouraging frequent creation. Mainstream Git workflows (Git Flow, GitHub Flow, Trunk-Based) are essentially different trade-offs in branching strategy. The 8 commands below cover 95% of branching scenarios: create, view, switch, delete, merge.

3.1 View Branches

git branch                       # List local branches (* marks current)
git branch -a                    # Local + remote branches
git branch -vv                   # Also show upstream tracking branch and latest commit
git branch --merged              # Branches already merged into current (safe to delete)
git branch --no-merged           # Unmerged branches (be careful before deleting)

3.2 Create & Switch

git branch feature/login                  # Create branch (don't switch)
git checkout feature/login                # Switch branch
git checkout -b feature/login             # Create and switch (most common)
git checkout -b feature/login origin/main # Create new branch based on remote main
git checkout -                            # Switch back to previous branch (saves history hunting)
git switch feature/login                  # New command in Git 2.23+, clearer semantics
git switch -c feature/login               # Equivalent to checkout -b

git checkout wears many hats (switch / restore files / check out remote), making it easy to confuse. Git 2.23+ introduced git switch (branch-only) and git restore (file-only) — recommended for new projects.

3.3 Delete & Rename

git branch -d feature/login       # Safe delete (only works if merged)
git branch -D feature/login       # Force delete (works even if unmerged, use with caution)
git branch -m new-name            # Rename current branch
git branch -m old new             # Rename old to new

3.4 Merge Branches

git merge feature/login                       # Merge feature/login into current branch
git merge --no-ff feature/login              # Disable fast-forward, preserve branch trace
git merge --squash feature/login             # Squash the whole branch into a single commit
git merge --abort                            # Abort after merge conflict, return to pre-merge state

--no-ff is very useful in Git branch management: even when fast-forward is possible, it forces a merge commit so git log --graph clearly shows "when this feature was merged in".

3.5 Real-World: Feature Branch Workflow

# 1. Create a new branch from main
git checkout main && git pull
git checkout -b feature/cart

# 2. Multiple commits to advance
git add . && git commit -m "feat(cart): add item list"
git add . && git commit -m "feat(cart): add checkout button"

# 3. Keep in sync with main (key: rebase freely before pushing)
git fetch origin
git rebase origin/main
# After resolving conflicts: git add . && git rebase --continue

# 4. Merge back into main (PR via GitHub is recommended; CLI shown here)
git checkout main
git merge --no-ff feature/cart
git push origin main
git branch -d feature/cart

4. Undo & Rollback (Must Read)

This is the most dangerous and most-searched section of Git commands. The essence of undo is "moving back the HEAD pointer, branch reference, staging area, and/or working directory to some previous state". The wrong flag can send unpushed code into a black hole — so please read carefully about the differences between the three git reset modes.

4.1 Discard Working Directory Changes (Safest)

git checkout -- file.txt          # Discard working dir changes for file.txt (legacy syntax)
git restore file.txt              # Recommended for Git 2.23+
git restore .                     # Discard all working dir changes
git restore --staged file.txt     # Unstage a staged file (keep modifications)

⚠️ Warning: git checkout -- file is irreversible — the file modifications will be permanently lost. For important changes, git stash first.

4.2 Unstage (Keep Working Directory)

git reset HEAD file.txt           # Unstage file.txt (keep working dir changes)
git restore --staged file.txt     # Same as above, new syntax
git reset                         # Unstage everything

4.3 Three Modes of git reset (Core)

git reset --soft HEAD~1           # Undo commit, keep changes in staging area
git reset --mixed HEAD~1          # Default mode: undo commit + unstage, keep changes in working dir
git reset --hard HEAD~1           # Undo commit + unstage + discard changes (irreversible!)
Modecommitstaging areaworking dir
--soft✗ undone✓ kept✓ kept
--mixed (default)✗ undone✗ undone✓ kept
--hard✗ undone✗ undone✗ undone (dangerous)

Memory trick: soft is softest (touches nothing), hard is hardest (clears everything). Looking for a commit accidentally deleted by --hard? See reflog.

4.4 git revert: Safely Undo a Pushed Commit

git revert <commit-hash>         # Create a new "reverse" commit, preserve history
git revert -m 1 <merge-hash>     # Revert a merge commit, -m 1 keeps the main branch
git revert --no-commit <hash>    # Revert without auto-commit, leaving it for you to handle

For commits already pushed to a public branch, never use git reset — it rewrites history and breaks your teammates. Using git revert is the etiquette of version control collaboration.

4.5 Amend the Last Commit

git commit --amend -m "new message"   # Change commit message
git add forgotten-file && git commit --amend --no-edit  # Add forgotten file
git commit --amend --no-edit          # Add files only, don't change message

--amend essentially means "discard the current HEAD commit and create a new one". It's only safe for commits not yet pushed.

4.6 Real-World: 3 Rollback Scenarios

# Scenario A: Wrong commit message, not yet pushed
git commit --amend -m "fix: correct message"

# Scenario B: Committed the wrong file, want to keep the file
git reset --soft HEAD~1
git restore --staged wrong-file
git commit -m "correct commit"

# Scenario C: Already pushed to main, want to undo this commit
git revert HEAD
git push origin main

5. Remote Repositories

This section brings together the Git commands commonly used for "remote collaboration": add remote, view remote, push, delete remote branch, tracking relationships. These are essential commands for collaboration on platforms like GitHub / GitLab / Gitee.

5.1 Add & View Remote

git remote -v                              # List all remotes (fetch + push URLs)
git remote add origin [email protected]:user/repo.git    # Add a remote
git remote add upstream [email protected]:upstream/repo.git  # Add upstream to a fork
git remote set-url origin <new-url>       # Change remote URL (common when switching HTTPS to SSH)
git remote remove origin                   # Remove a remote
git remote rename origin my-origin         # Rename a remote

5.2 Push & Tracking

git push -u origin main                    # First push + set upstream
git push                                   # Subsequent pushes, just git push
git push origin --all                      # Push all local branches
git push origin --tags                     # Push all tags
git push origin --delete feature/old       # Delete a remote branch
git push origin :feature/old               # Old syntax, equivalent to --delete

5.3 Pull & Sync

git pull                                   # = fetch + merge
git pull --rebase                          # = fetch + rebase (recommended)
git pull --rebase --autostash              # Auto-stash before pull, auto-pop after
git fetch --all                            # Fetch all remotes
git fetch --prune                          # Clean up refs to deleted remote branches
git fetch origin feature/login:my-feature  # Fetch a remote branch to a local name

5.4 Real-World: Sync a Fork with Upstream

# 1. One-time setup
git remote add upstream [email protected]:original/repo.git

# 2. Sync main branch
git fetch upstream
git checkout main
git merge upstream/main
git push origin main

6. Advanced & Troubleshooting

This section is the "lifeline" area of any Git command cheat sheet: git reflog has rescued countless commits accidentally deleted by --hard, git rebase -i can collapse 5 commits into 1, and git cherry-pick lets you move a single commit from someone else's branch to yours.

6.1 git reflog: The Life-Saver

git reflog                                 # Show all HEAD historical movements
git reset --hard HEAD@{5}                  # Return to the state at step 5 in reflog
git reflog expire --expire=now --all && git gc --prune=now --aggressive  # Clean up reflog

Every reset / checkout / merge leaves a record in reflog. Even if a commit was deleted by reset --hard, as long as it hasn't expired (default 90 days), it can be recovered from reflog — the most powerful "regret pill" in version control.

6.2 git cherry-pick: Move a Single Commit

git cherry-pick <commit-hash>             # Apply the specified commit to current branch
git cherry-pick <hash1> <hash2>            # Move multiple commits at once
git cherry-pick -x <hash>                  # Add (cherry picked from commit xxx) annotation
git cherry-pick --abort                    # Abort after conflict
git cherry-pick --continue                 # Continue after resolving conflict

6.3 git rebase -i: Interactive History Cleanup

git rebase -i HEAD~3                       # Edit the last 3 commits
# In the editor that pops up, change pick to:
#   pick = keep
#   reword = change message
#   edit = pause to modify content
#   squash = merge into previous
#   drop = delete

git rebase -i origin/main                  # Rebase your branch onto main

Golden rule: Only run git rebase on commits not yet pushed to a public branch. Rebasing pushed commits will fork the local history of all collaborators.

6.4 git tag: Version Tagging

git tag v1.0                              # Lightweight tag
git tag -a v1.0 -m "Release 1.0"          # Annotated tag (recommended, includes author, message, GPG signature)
git tag -a v1.1 <commit-hash> -m "1.1"    # Tag a historical commit
git tag                                    # List all tags
git tag -l "v1.*"                          # Glob matching
git show v1.0                              # View tag details
git push origin v1.0                       # Push a single tag
git push origin --tags                     # Push all tags
git tag -d v1.0                            # Delete local tag
git push origin :refs/tags/v1.0            # Delete remote tag

6.5 .gitignore: Ignore Files

# Create .gitignore in project root
node_modules/
dist/
.env
*.log
.DS_Store
.idea/
.vscode/

# For files already accidentally committed, remove from repo but keep locally
git rm --cached file.txt
git rm -r --cached node_modules/
git commit -m "chore: update gitignore"

# Force-add an ignored file
git add -f secret-config.json

6.6 Real-World: Resolve Merge Conflicts

# 1. Trigger conflict
git merge feature/login
# Auto-merging src/app.ts
# CONFLICT (content): Merge conflict in src/app.ts
# Automatic merge failed; fix conflicts and then commit.

# 2. View conflicting files
git status
# both modified:   src/app.ts

# 3. Open file, you'll see conflict markers:
# <<<<<<< HEAD
# console.log("main version");
# =======
# console.log("feature version");
# >>>>>>> feature/login

# 4. Manually edit to the final version, delete the <<<<<<< / ======= / >>>>>>> marker lines

# 5. Mark resolved + complete the merge
git add src/app.ts
git commit                      # merge scenario
git rebase --continue           # rebase scenario
git merge --abort               # Give up, return to pre-merge state

6.7 Other High-Frequency Commands

git show <hash>                          # View changes in a specific commit
git shortlog -sn                          # Count commits per author
git clean -fd                             # Delete untracked files and directories (dangerous)
git fsck --lost-found                     # Recover dangling objects (ultimate life-saver)
git config --list --show-origin           # View all configuration + source file

7. Frequently Asked Questions (FAQ)

Q1: What's the difference between git pull and git fetch + git merge?

git fetch only downloads remote commits to your local remote-tracking branches (like origin/main); it doesn't touch your working directory or current branch. git merge is what actually brings those changes into your current branch. git pull = git fetch + git merge in one step. So git pull is more convenient but more of a "black box"; when you need precise control to debug issues, splitting it into fetch + merge is recommended.

Q2: What's the difference between git merge and git rebase? When should I use each?

Both serve the same purpose — bringing changes from one branch into another — but produce different histories: git merge creates a merge commit and preserves the fork record (good for main / public branches); git rebase "replays" the current branch's commits on top of the target branch, producing a clean linear history (good for local feature branches or keeping main linear). Rule of thumb: rebase freely on local unpushed branches, merge only on pushed ones.

Q3: How do I recover a commit accidentally deleted by git reset --hard?

Run git reflog immediately, find the commit hash from before the reset (e.g. abc1234), then git reset --hard abc1234. reflog is kept for 90 days by default, so nearly all "lost commit from misoperation" scenarios can be rescued. The only truly unrecoverable cases are: reflog cleared, or objects garbage-collected by git gc.

Q4: How do I undo a commit that's already been pushed?

Use git revert <commit-hash> — it creates a new "reverse" commit that undoes the changes, then you can git push normally. Advantage: doesn't rewrite history, teammates' local repos are unaffected. Never use git reset --hard + force push on a public branch that's already been pushed — it forks the history of all collaborators.

Q5: SSH or HTTPS — which is better?

In the short term, HTTPS is simpler (account + password) and suitable for beginners. In the long run, SSH is more convenient (one-time key setup, then git push without password), and CI/CD scenarios almost always require SSH. The two are functionally equivalent — pick per your team's standards. When you frequently switch accounts (e.g. maintaining both personal and work accounts), HTTPS + Personal Access Token can actually be more flexible.

8. Recommended Tools

After reading this Git cheat sheet, the 50 commands above are enough for daily repository operations — but a developer's toolbox goes well beyond Git. Below are several online tools on DevToolbox closely related to version control and document collaboration — 100% client-side processing, zero data upload, safe for pasting code and documents.

More tools at the DevToolbox homepage. Wishing you smooth Git workflows — with commit messages always properly formatted and never shipping debug code :)

🔗 Share: 𝕏 📘 ✈️ 💬

FAQ: Common Questions

Q: Git 是什么?

Git 是 2005 年 Linus Torvalds 发布的分布式版本控制系统,主流代码管理工具。被 GitHub、GitLab、Bitbucket 等平台全面支持。

Q: Git 和 SVN 有什么区别?

Git 分布式(每人完整仓库),SVN 集中式(中央服务器)。Git 分支廉价秒建,SVN 分支是目录拷贝。Git 离线工作,SVN 必须联网。

Q: 如何撤销 Git 提交?

git revert <hash>(生成反向提交,安全用于已推送的)、git reset --soft HEAD~1(撤销 commit 保留改动)、git reset --hard HEAD~1(彻底删除,慎用)。

🧰
Add to Home Screen
Works offline, launches instantly