git status命令

git status命令用於顯示工作目錄和暫存區的狀態。使用此命令能看到那些修改被暫存到了, 哪些沒有, 哪些文件沒有被Git tracked到。git status不顯示已經commit到項目歷史中去的信息。看項目歷史的信息要使用git log.

簡介

git status [<options>…​] [--] [<pathspec>…​]

描述

顯示索引文件和當前HEAD提交之間的差異,在工作樹和索引文件之間有差異的路徑以及工作樹中沒有被Git跟蹤的路徑。 第一個是通過運行git commit來提交的; 第二個和第三個是你可以通過在運行git commit之前運行git add來提交的。

git status相對來說是一個簡單的命令,它簡單的展示狀態信息。輸出的內容分爲3個分類/組。

# On branch master
# Changes to be committed:  (已經在stage區, 等待添加到HEAD中的文件)
# (use "git reset HEAD <file>..." to unstage)
#
#modified: hello.py
#
# Changes not staged for commit: (有修改, 但是沒有被添加到stage區的文件)
# (use "git add <file>..." to update what will be committed)
# (use "git checkout -- <file>..." to discard changes in working directory)
#
#modified: main.py
#
# Untracked files:(沒有tracked過的文件, 即從沒有add過的文件)
# (use "git add <file>..." to include in what will be committed)
#
#hello.pyc

忽略文件(untracked文件)

沒有tracked的文件分爲兩類. 一是已經被放在工作目錄下但是還沒有執行 git add 的, 另一類是一些編譯了的程序文件(如.pyc, .obj, .exe等)。當這些不想add的文件一多起來, git status的輸出簡直沒法看, 一大堆的狀態信息怎麼看?

基於這個原因。 Git讓我們能在一個特殊的文件.gitignore中把要忽略的文件放在其中, 每一個想忽略的文件應該獨佔一行, *這個符號可以作爲通配符使用。例如在項目根目錄下的.gitignore文件中加入下面內容能阻止.pyc.tmp文件出現在git status中:

*.pyc
*.tmp

示例

以下是一些示例 -

在每次執行 git commit之前先使用git status檢查文件狀態是一個很好的習慣, 這樣能防止你不小心提交了您不想提交的東西。 下面的例子展示 stage 前後的狀態, 並最後提交一個快照.


# Edit hello.py
$ git status
# hello.py is listed under "Changes not staged for commit"
$ git add hello.py
$ git status
# hello.py is listed under "Changes to be committed"
$ git commit
$ git status
# nothing to commit (working directory clean)

第一個狀態輸出顯示了這個文件沒有被放到暫存區(staged)。git add將影響第二個git status的輸出, 最後一個git status告訴我們沒有什麼能可以提交了,工作目錄已經和最近的提交相匹配了。有些命令 (如, git merge) 要求工作目錄是clean狀態, 這樣就不會不小心覆蓋更新了。

git status命令可以列出當前目錄所有還沒有被git管理的文件和被git管理且被修改但還未提交(git commit)的文件。下面來看看如下一個示例 -

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#       modified:   2.txt
#
# Changes not staged for commit:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       modified:   1.txt
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       1.log

上面輸出結果中」Changes to be committed「中所列的內容是在索引中的內容,提交之後進入Git工作目錄。
上面輸出結果中「Changed but not updated」中所列的內容是在工作目錄中的內容,git add之後將添加進入索引。
上面輸出結果中「Untracked files」中所列的內容是尚未被Git跟蹤的內容,git add之後進入添加進入索引。
通過git status -uno可以只列出所有已經被git管理的且被修改但沒提交的文件。