Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Git: Check programmatically if anything is staged

Tags:

git

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.

like image 496
Ram Rachum Avatar asked Nov 27 '16 23:11

Ram Rachum


People also ask

What command can you use to see what changes have been 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.

What is git status porcelain?

" 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.


2 Answers

You're looking for:

git diff --cached --quiet

(or replace --quiet with --exit-code if you still want output)

like image 118
o11c Avatar answered Oct 20 '22 06:10

o11c


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 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!

like image 30
J.Baoby Avatar answered Oct 20 '22 07:10

J.Baoby