Git 命令速查
Git 将文件变更记录为仓库里的一系列提交。这些命令覆盖日常流程:建仓、保存改动、分支、合并以及与远端共享。学习时把本表放在手边。
| 命令 | 作用 |
|---|---|
| git init | Create a new, empty Git repository in the current directory. |
| git clone | Download a remote repository and its full history to your machine. |
| git status | Show changed, staged and untracked files in the working tree. |
| git add | Stage changes (files) to be included in the next commit. |
| git commit | Record staged changes as a new commit with a message. |
| git log | Display the commit history of the repository. |
| git diff | Show unstaged or staged differences between states. |
| git branch | List, create or delete branches in the repository. |
| git checkout / switch | Switch branches or restore files (switch is the modern command). |
| git merge | Join another branch's history into the current branch. |
| git rebase | Reapply commits on top of another base commit, rewriting history. |
| git pull | Fetch from a remote and merge the changes into the current branch. |
| git push | Upload local commits to a remote repository. |
| git stash | Temporarily shelve uncommitted changes to reapply later. |
| git remote | Manage the set of remote repositories you track. |
说明
- 多数命令支持参数(如 -m 写信息、-a 全部);运行 'git help <命令>' 看完整列表。
- 分支名很轻量、可随意丢弃——常在功能分支上提交,再合并回主分支。
- 在执行 rebase、reset 等破坏性命令前,先确保工作已提交或暂存。
常见问题
- merge 和 rebase 有什么区别?
- merge 用一个有两个父节点的新提交合并历史。rebase 把你的提交重放到另一分支之上,得到线性历史,但会改写提交的 ID。
- 如何撤销一次提交?
- 用 'git revert <提交>' 新增一个反向提交来撤销改动(安全,保留共享历史)。'git reset' 会改写历史,不应在共享分支上使用。
- git pull 和 git fetch 有何不同?
- fetch 从远端下载提交与引用,但不动你的工作区。pull 先 fetch,再把改动合并或变基到当前分支。
- 什么时候用 git stash?
- stash 临时搁置未提交的改动,方便切换分支或干净地拉取代码,之后用 'git stash pop' 取回。