For a Git script I'm writing, I'd like to have a programmatic way to check whether there is anything at all staged. i.e. 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.
The git status command displays the state of the working directory and the staging area. It lets you see which changes have been staged, which haven't, and which files aren't being tracked by Git.
" git status --branch --porcelain " displays the status of the branch (ahead, behind, gone), and used gettext to translate the string. Use hardcoded strings when --porcelain is used, but keep the gettext translation for " git status --short " which is essentially the same, but meant to be read by a human.
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 (i.e. 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 caseXY
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With