DevToolBox免费
博客

Git 命令生成器 -- 可视化构建 Git 命令

18 分钟阅读作者 DevToolBox
TL;DR

The Git Command Generator lets you build complex Git commands visually -- no memorization required. Pick an operation (commit, branch, merge, rebase, stash, cherry-pick, reset, log, etc.), set flags through a point-and-click interface, and copy the resulting command in one click. Below you will find a comprehensive reference covering every essential Git command category, collaboration workflows, and productivity tips that pair perfectly with the generator.

Key Takeaways
  • A visual Git command builder eliminates syntax errors and speeds up complex operations like interactive rebase, cherry-pick ranges, and advanced log formatting.
  • Understanding the staging area, HEAD, refs, and the reflog is fundamental to mastering any git commands list.
  • Branching strategies (feature-branch, trunk-based, GitFlow) determine how teams collaborate and ship code safely.
  • Git hooks automate quality checks (linting, testing, commit message validation) before code ever reaches a remote.
  • Worktrees let you work on multiple branches simultaneously without stashing or switching context.
  • Git aliases and custom log formats turn repetitive multi-flag commands into one-word shortcuts.

Essential Git Commands Every Developer Should Know

Whether you are onboarding at a new company or contributing to open-source for the first time, a solid understanding of the core git commands is non-negotiable. The list below covers daily operations that make up roughly 90% of every developer's workflow.

Repository Initialization and Cloning

# Create a brand-new repo in the current directory
git init

# Clone a remote repository (HTTPS)
git clone https://github.com/user/repo.git

# Clone only the latest commit -- great for CI
git clone --depth 1 https://github.com/user/repo.git

# Clone a specific branch
git clone -b develop --single-branch https://github.com/user/repo.git

Staging, Committing, and Status

The staging area (index) is Git's middle ground between the working directory and the repository. Learning to stage selectively produces cleaner history.

git status                  # check working directory
git add file.txt src/       # stage specific files
git add -A                  # stage everything
git add -p file.txt         # interactive hunk staging

git commit -m "feat: add user authentication"
git commit -am "fix: typo"  # stage tracked + commit
git commit --amend --no-edit # amend last commit silently
Tip: Use the Git Command Generator to visually compose these commands with all the right flags -- no copy-paste from Stack Overflow needed.

Viewing History and Diffing

# Compact one-line log with graph
git log --oneline --graph --decorate --all

# Filter by author or date
git log --author="alice" --since="2026-01-01"

# Search commit messages
git log --grep="authentication"

# Custom pretty format
git log --pretty=format:"%h %ad | %s%d [%an]" --date=short

# Diff staged changes vs last commit
git diff --staged

# Compare two branches (file names only)
git diff --name-only main..HEAD

Branching and Merging -- The Heart of Collaboration

Branches are cheap in Git -- they are simply pointers to commits. Mastering branch operations is essential for parallel development and clean code integration.

Branch Management

# List all branches (local + remote)
git branch -a

# Create and switch to a new branch
git switch -c feature/login

# Rename current branch
git branch -m new-name

# Delete a merged / unmerged branch
git branch -d feature/login   # safe delete
git branch -D feature/login   # force delete

# Track a remote branch locally
git checkout --track origin/develop

Merging Strategies

git merge feature/login              # fast-forward if possible
git merge --no-ff feature/login      # always create merge commit
git merge --squash feature/login     # squash into one commit
git merge --abort                    # cancel merge in progress
git merge -X theirs feature/login    # auto-resolve with theirs
Best practice: Use --no-ff merges on shared branches so the feature boundary is always visible in the graph.

When merge conflicts arise, Git marks conflicting sections with <<<<<<< / ======= / >>>>>>> markers. Resolve them manually or with git mergetool, then git add the resolved files and commit.

Rebasing -- Rewriting History for a Clean Timeline

Where git merge preserves the complete branching history, git rebase replays your commits on top of another branch to create a linear sequence. The result is a cleaner, easier-to-read log.

Standard Rebase

# Rebase current branch onto main
git rebase main

# Rebase onto a specific commit
git rebase --onto main feature/base feature/child

# Continue after resolving conflicts
git rebase --continue

# Skip the current commit during rebase
git rebase --skip

# Abort the entire rebase
git rebase --abort

Interactive Rebase

Interactive rebase (git rebase -i) lets you rewrite, reorder, squash, or drop commits. It is the single most powerful history-editing tool in Git.

# Interactive rebase for the last 5 commits
git rebase -i HEAD~5

# Available commands in the interactive editor:
# pick   = keep commit as-is
# reword = keep commit but edit message
# edit   = pause to amend the commit
# squash = meld into previous commit (keep message)
# fixup  = meld into previous commit (discard message)
# drop   = remove the commit entirely

# Autosquash: automatically reorder fixup! and squash! commits
git rebase -i --autosquash HEAD~10
Warning: Never rebase commits that have already been pushed to a shared branch. Rebasing rewrites commit hashes, which forces everyone else to reconcile divergent histories.

Cherry-Pick -- Surgical Commit Transplants

git cherry-pick copies individual commits from one branch to another. It is ideal for back-porting hotfixes or selectively pulling in work without merging an entire branch.

# Cherry-pick a single commit
git cherry-pick abc1234

# Cherry-pick without committing (stage only)
git cherry-pick --no-commit abc1234

# Cherry-pick a range of commits
git cherry-pick abc1234..def5678

# Cherry-pick from another branch by commit hash
git cherry-pick feature/payments~3

# Abort a cherry-pick in progress
git cherry-pick --abort

# Continue after resolving conflicts
git cherry-pick --continue

Git Stash -- Shelving Work in Progress

When you need to switch branches but are not ready to commit, git stash saves your uncommitted changes to a temporary stack.

# Stash with a descriptive message
git stash push -m "WIP: refactoring auth module"

# Stash including untracked files
git stash -u

# List all stashes
git stash list

# Apply and remove from stack
git stash pop

# Apply a specific stash (keep in stack)
git stash apply stash@{2}

# Show diff of a stash
git stash show -p stash@{0}

# Create a branch from a stash
git stash branch new-feature stash@{1}

# Clear all stashes
git stash clear

Reset vs Revert -- Undoing Changes the Right Way

Both git reset and git revert undo changes, but they operate very differently. Understanding which to use is critical, especially on shared branches.

git reset -- Moving HEAD Backward

git reset --soft HEAD~1    # uncommit, keep staged
git reset HEAD~1           # uncommit + unstage (default)
git reset --hard HEAD~1    # discard everything
git restore --staged file  # unstage a single file

git revert -- Safe History Undo

git revert abc1234                  # undo commit (new commit)
git revert --no-commit abc1234      # stage undo without committing
git revert -m 1 <merge-commit-sha>  # revert a merge commit
Aspectgit resetgit revert
History modificationRewrites historyPreserves history
Safe for shared branchesNoYes
Creates new commitNoYes
Use caseLocal cleanupUndo on public branches

Git Log Formatting -- Custom Output for Every Workflow

The --pretty=format flag unlocks a mini template language. Key placeholders: %h (short hash), %an (author), %ad (date), %s (subject), %d (decorations), %Cgreen/%Creset (colors).

# Changelog-style
git log --pretty=format:"%Cgreen%h%Creset %s (%Cblue%an%Creset, %ar)"

# JSON output for scripting
git log --pretty=format:'{"hash":"%h","author":"%an","msg":"%s"}' --date=iso

# Only merge commits / only non-merge commits
git log --merges --oneline
git log --no-merges --oneline

Git Aliases -- One-Word Shortcuts for Complex Commands

Git aliases let you abbreviate any command. They live in ~/.gitconfig and can save thousands of keystrokes per week.

Define aliases directly in ~/.gitconfig:

[alias]
  co  = checkout
  br  = branch
  ci  = commit
  st  = status
  lg  = log --oneline --graph --decorate --all
  last = log -1 HEAD --stat
  undo = reset --soft HEAD~1
  oops = commit --amend --no-edit
  today = log --since=midnight --oneline
  ds  = diff --staged
  wip = !git add -A && git commit -m "WIP: work in progress"
  cleanup = !git branch --merged main | grep -v main | xargs git branch -d

Interactive Staging -- Craft Precise Commits

Interactive staging with git add -p (patch mode) lets you review each change hunk by hunk and decide whether to stage it. This results in atomic, self-contained commits that are easier to review and revert.

# Enter patch mode -- review each hunk
git add -p
# y=stage, n=skip, s=split, e=edit, q=quit

# Interactive staging with full menu
git add -i

# Unstage specific hunks selectively
git reset -p

Pair interactive staging with a visual builder: the Git Command Generator shows you every available flag for git add so you never miss an option.

Git Worktrees -- Multiple Branches, Zero Stashing

git worktree lets you check out multiple branches simultaneously in separate directories. This is a game-changer when you need to review a pull request while your feature branch has uncommitted work.

# Add a new worktree for an existing branch
git worktree add ../hotfix hotfix/urgent-fix

# Add a worktree with a new branch
git worktree add -b feature/new-ui ../new-ui main

# List all worktrees
git worktree list

# Remove a worktree
git worktree remove ../hotfix

# Prune stale worktree references
git worktree prune
Workflow tip: Create a directory layout like project-main/, project-feature/, and project-review/ so each worktree has a clear purpose.

Git Submodules -- Managing Dependencies as Repos

Submodules let you embed one Git repository inside another. They are commonly used for shared libraries, design systems, or vendored dependencies.

# Add a submodule
git submodule add https://github.com/lib/shared-utils.git libs/shared

# Clone a repo including its submodules
git clone --recurse-submodules https://github.com/user/repo.git

# Initialize + update after a regular clone
git submodule init && git submodule update

# Update all submodules to latest remote commit
git submodule update --remote --merge

# Remove a submodule completely
git submodule deinit libs/shared
git rm libs/shared
Caution: Submodules add complexity. For many use cases, package managers (npm, pip, go modules) or monorepo tools (Nx, Turborepo) are simpler alternatives.

Git Hooks -- Automate Quality Gates

Git hooks are scripts that run automatically at specific points in the Git workflow. They live in .git/hooks/ and can enforce coding standards, run tests, and validate commit messages before code reaches the remote.

Key hooks: pre-commit (lint/format before commit), commit-msg (validate commit messages), pre-push (run tests before push), post-merge (auto-install dependencies).

Example: pre-commit Hook with Husky

# Install Husky for shareable hooks
npx husky-init && npm install

# Add lint-staged as a pre-commit hook
npx husky add .husky/pre-commit "npx lint-staged"

# Validate commit messages (Conventional Commits)
npx husky add .husky/commit-msg 'npx --no -- commitlint --edit "$1"'

Collaboration Workflows -- Choosing the Right Strategy

How a team organizes branches determines code quality, release cadence, and developer experience. Here are the three most popular approaches.

1. Feature Branch Workflow

Every feature or bug fix gets its own branch from main. A pull request is opened, reviewed, and merged.

git switch -c feature/user-profile
git add . && git commit -m "feat: add user profile page"
git push -u origin feature/user-profile
# After PR approval:
git switch main && git merge --no-ff feature/user-profile

2. Trunk-Based Development

Developers commit directly to main (or use very short-lived branches). Feature flags control which code is active in production. This approach favors continuous integration and reduces merge conflicts.

# Work directly on main with small, frequent commits
git switch main
git pull --rebase origin main
git add .
git commit -m "feat: add profile avatar behind feature flag"
git push origin main

3. GitFlow

GitFlow uses dedicated branches for features, releases, and hotfixes. It is well-suited for projects with scheduled releases and multiple supported versions.

# Feature: branch from develop, merge back
git switch -c feature/payment develop
# ... work ...
git switch develop && git merge --no-ff feature/payment

# Release: branch from develop, merge into main + develop
git switch -c release/1.2.0 develop
git switch main && git merge --no-ff release/1.2.0
git tag -a v1.2.0 -m "Release 1.2.0"
git switch develop && git merge --no-ff release/1.2.0

# Hotfix: branch from main, merge into main + develop
git switch -c hotfix/fix-crash main
git switch main && git merge --no-ff hotfix/fix-crash
git tag -a v1.2.1 -m "Hotfix 1.2.1"
git switch develop && git merge --no-ff hotfix/fix-crash
WorkflowBest ForMerge StyleComplexity
Feature BranchMost teamsPR-based mergeLow
Trunk-BasedCI/CD-heavy teamsDirect push / short PRsLow
GitFlowScheduled releasesMultiple long-lived branchesHigh

Remote Operations -- Syncing with the World

# Add a remote
git remote add upstream https://github.com/original/repo.git

# Fetch and prune deleted remote branches
git fetch --prune

# Pull with rebase (cleaner history)
git pull --rebase origin main

# Push and set upstream tracking
git push -u origin feature/login

# Delete a remote branch
git push origin --delete feature/login

# Safe force push (refuses if remote has new commits)
git push --force-with-lease origin feature/login

Tags and Releases

# Create an annotated tag (recommended)
git tag -a v1.0.0 -m "Production release 1.0.0"

# Tag a specific commit
git tag -a v0.9.0 abc1234 -m "Beta release"

# List tags matching a pattern
git tag -l "v1.*"

# Push all tags to remote
git push origin --tags

# Delete a local + remote tag
git tag -d v1.0.0
git push origin --delete v1.0.0

Advanced Git Commands -- Reflog, Bisect, and Clean

git reflog -- Your Safety Net

The reflog records every movement of HEAD. Even after a hard reset or bad rebase, you can recover lost commits.

git reflog                          # view reflog
git switch -c recovered <sha>       # recover a lost commit

git bisect -- Binary Search for Bugs

git bisect start
git bisect bad                      # current commit is broken
git bisect good v1.0.0              # this commit was OK
# Git checks out midpoints -- mark good/bad until culprit found
git bisect reset                    # done

# Automate: run test at each midpoint
git bisect start HEAD v1.0.0
git bisect run npm test

git clean -- Remove Untracked Files

git clean -n    # dry run
git clean -fd   # remove untracked files + directories
git clean -fdX  # also remove ignored files

Git Commands List -- Quick Reference

Bookmark this page as your printable git cheat sheet, or generate any command visually with the Git Command Generator.

CategoryCommandPurpose
Initgit initCreate new repo
Clonegit clone <url>Copy remote repo
Stagegit add -AStage all changes
Commitgit commit -m "msg"Record changes
Branchgit switch -c <name>Create + switch branch
Mergegit merge --no-ff <branch>Merge with commit
Rebasegit rebase mainReplay on top of main
Stashgit stash push -m "msg"Shelve WIP
Cherry-pickgit cherry-pick <sha>Copy single commit
Resetgit reset --soft HEAD~1Undo commit, keep staged
Revertgit revert <sha>Undo commit safely
Taggit tag -a v1.0.0 -m "msg"Mark a release
Worktreegit worktree add <path> <branch>Multi-branch checkout
Bisectgit bisect startBinary search for bugs
Refloggit reflogRecover lost commits

Using the Git Command Generator Tool

The Git Command Generator lets you select an operation, toggle flags visually, and copy the resulting command. Each flag includes a description so you learn Git syntax naturally -- no memorization required.

Frequently Asked Questions

What is the difference between git merge and git rebase?

git merge joins two branch histories by creating a merge commit, preserving the complete branching structure. git rebase replays your commits on top of another branch, producing a linear history without merge commits. Use merge on shared branches for safety; use rebase on local feature branches for cleanliness.

How do I undo the last git commit without losing changes?

Run git reset --soft HEAD~1. This moves HEAD back one commit but keeps all changes staged. If you want to unstage them as well, use git reset HEAD~1 (mixed mode, the default). To discard changes entirely, use git reset --hard HEAD~1 -- but be careful, this is irreversible.

What are the most important git commands for beginners?

Start with these ten: git init, git clone, git add, git commit, git status, git log, git branch, git switch, git merge, and git push. These cover creating repos, making changes, viewing history, branching, and syncing with remotes.

How do I create a git cheat sheet for my team?

Combine the quick reference table above with your team's specific conventions (branch naming, commit message format, merge strategy). Store it in your project's CONTRIBUTING.md or wiki. Alternatively, use the Git Command Generator as a living, interactive cheat sheet that everyone can bookmark.

When should I use git stash vs creating a WIP commit?

Use git stash for quick context switches when you plan to return to the same branch shortly. Create a WIP commit when you want your progress tracked in the branch history (you can always squash it later with interactive rebase). Stashes are local-only and easy to lose; WIP commits travel with the branch to the remote.

How does git cherry-pick differ from git merge?

git merge brings an entire branch's changes into the current branch. git cherry-pick copies individual commits by their SHA hash, leaving the source branch untouched. Cherry-pick is best for back-porting specific fixes; merge is best for integrating complete features.

What is git reflog and how does it save me?

git reflog is a local log of every position HEAD has pointed to. Even after a hard reset, force push, or bad rebase, you can find the SHA of the state you want and check it out. Think of it as Git's undo history -- it records actions that git log does not track, like branch deletions and rebases.

𝕏 Twitterin LinkedIn
这篇文章有帮助吗?

保持更新

获取每周开发技巧和新工具通知。

无垃圾邮件,随时退订。

试试这些相关工具

🔀Git Command Generator

相关文章

Git 命令速查表:开发者必备命令大全

完整的 Git 命令速查表:涵盖配置、分支、合并、变基、暂存和高级工作流程。

Git Rebase vs Merge:何时使用哪个(图解对比)

理解 git rebase 和 merge 的区别。学习何时使用哪个,避免常见陷阱,掌握 Git 工作流。

Git cherry-pick、revert 和 reset 详解

学习何时以及如何使用 git cherry-pick、revert 和 reset。理解每个命令的区别、用例和安全注意事项。

Git 分支命名规范与策略

Git 分支命名最佳实践。学习 feature/bugfix/hotfix 前缀、Git Flow vs GitHub Flow,以及团队协作分支策略。

Git 撤销最后一次提交:5 种保留更改的修复方法

学习五种撤销最后一次 git 提交并保留更改的方法。涵盖 git reset --soft、git revert、git amend、交互式 rebase 和 reflog 恢复。

.gitignore 模板与常用忽略规则大全

全面的 .gitignore 模板和常用忽略规则集合,涵盖 Node.js、Python、Java、Go 等,可直接复制使用。