在 Git 的日常使用中,git status 是使用频率最高的命令,没有之一。它就像汽车仪表盘上的指示灯,时刻告诉你车辆当前的运行状态。
在实际工作中,我们强烈建议:在任何操作(如 add、commit、pull)前后,都习惯性地敲一下这个命令,确认当前状态是否符合预期,避免误操作。
直接输入命令,查看当前仓库的完整状态:
git status
Git 会输出一份详细的报告,主要包含以下三个部分:
(1) 当前分支信息
输出第一行通常会显示你所在的分支:
On branch master
这表示你当前在 master 分支上工作。
(2) 暂存区状态
如果你执行过 git add,文件会显示在这里:
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
new file: README.md
(3) 工作区状态 这里有三种常见情况:
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: index.html
Untracked files:
(use "git add <file>..." to include in what will be committed)
config.env
git status 的输出信息虽然详细,但有时候过于冗长。当你只需要快速浏览文件状态时,可以使用 -s 参数:
git status -s
输出示例:
M index.html
A README.md
D style.css
?? test.log
这种紧凑的格式通过左侧的两个字母栏位来表示状态:
| 标记 | 含义解释 |
|---|---|
?? |
未跟踪:新文件,Git 尚未管理。 |
A |
新添加:新文件已添加到暂存区,准备首次提交。 |
M |
修改:文件内容发生了改变。 |
D |
删除:文件已被删除。 |
解读技巧: 输出分为左右两栏。
- 左栏(绿色):表示暂存区的状态。例如 M 在左列,表示修改已暂存。
- 右栏(红色):表示工作区的状态。例如 M 在右列,表示修改了但未暂存。
- MM:如果两边都有 M,表示文件已暂存,但暂存后工作区又有了新的修改。
让我们通过一个实际操作流程,感受状态的变化:
1. 初始状态:
执行 git status,显示:
nothing to commit, working tree clean
nothing to commit, working tree clean
(工作区很干净,没有任何未提交的修改。)
2. 修改文件: 修改 index.html 后,执行 git status:
Changes not staged for commit:
modified: index.html
(检测到修改,状态为红色。)
3.添加到暂存区:
执行 git add index.html,再次 git status:
Changes to be committed:
modified: index.html
(修改已确认,状态变为绿色。)
4. 再次修改:
如果你这时又改了一下 index.html 并保存,git status 会显示:
Changes to be committed:
modified: index.html
Changes not staged for commit:
modified: index.html
(同一个文件同时出现在暂存区和工作区!这表示暂存区里有一个版本,工作区里又有一个新版本。如果你想提交最新的版本,需要再次 git add。)