Git: Check programmatically if anything is staged
For a Git script I'm writing, I'd like to have a programmatic way to check whether there is anything at all staged. ie I want a positive result if anything at all is staged, and negative if nothing is staged.
Bonus points: A way to programmatically check whether there is anything new in the working tree that can be staged.
You're looking for:
git diff --cached --quiet
(or replace --quiet
with --exit-code
if you still want output)
The short format output of the git status
(also explained in helppage git status --help
) command gives an output that can be used in a programmatic way. From the git status --help
helppage (somewhere at the bottom of the page in the "OUTPUT"-section, for my git version 2.8.1.windows.1):
In the short-format, the status of each path is shown as
XY PATH1 -> PATH2
where PATH1 is the path in the HEAD, and the " -> PATH2" part is shown only when PATH1 corresponds to a different path in the index/worktree (ie the file is renamed). The XY is a two-letter status code.
According to the same helppage:
For paths with merge conflicts, X and Y show the modification states of each side of the merge. For paths that do not have merge conflicts, X shows the status of the index, and Y shows the status of the work tree. For untracked paths, XY
are ??
. Other status codes can be interpreted as follows:
' '
= unmodified
M
= modified
A
= added
D
= deleted
R
= renamed
C
= copied
U
= updated but unmerged
Ignored files are not listed, unless --ignored option is in effect, in which case XY
are !!
.
All this info about the values XY
can take can also be found here. The short format is obtained by using git status -s
. So
git status -s | grep "^[MADRCU]"
Should give you all entries that have been staged so far. You could add the -c
flag to the grep to count the lines instead of printing them.
Bonus: anything new in the working tree that hasn't been staged yet (still untracked) should be found with:
git status -s | grep "^??"
Hope this helps.
Good luck!
链接地址: http://www.djcxy.com/p/50886.html上一篇: 跟踪但不要使用git分档文件?
下一篇: Git:以编程方式检查是否有任何事件发生