git count files in the staged index

Git

Git Problem Overview


I'm trying to figure out how to easily count the files in my uncommitted index.

I've tried:

git status | grep '#' | wc -l

but there are a few lines that start with # that don't represent changed files. Anyone got anything better? Figured there had to be a flag for git status to do this.

Even tools like GitX don't easily allow you to select the staged files/directories and see how many of them there are.

Git Solutions


Solution 1 - Git

If you want something a script can use:

git diff --cached --numstat | wc -l

If you want something human readable:

git diff --cached --stat

Solution 2 - Git

This worked for me:

git status | grep 'modified:' | wc -l

it returns a number

Solution 3 - Git

For what it's worth, I prefer:

git diff --stat | tail -n1

Outputs something like:

10 files changed, 74 insertions(+), 123 deletions(-)

Solution 4 - Git

Try git status -s:

git status -s | egrep "^M" | wc -l

M directly after start-of-line (^) indicates a staged file. ^ M, with a space, would be an unstaged but changed file.

Solution 5 - Git

This has lots of answers... but the best command imo (it doesn't require any piping and is a pure native git command) is just the following. Note that this counts deleted, modified, and added files:

git diff --cached --shortstat

The output is only one line:

X files changed, Y insertions(+), Z deletions(-)

If no changes have been made, it prints nothing (not even a new empty line).

It's also obvious how to get the same result for unstaged changes (just omit the --cached flag):

git diff --shortstat

Solution 6 - Git

Maybe it was not available 9 years ago, but as of 2019, ls-files is much faster than diff --stat:

git ls-files --cached | wc -l

Solution 7 - Git

For anyone looking for a PowerShell solution:

(git diff --cached --numstat | Measure-Object -Line).Lines

Solution 8 - Git

Below should cover for all cases (new, modified, deleted and even untracked), it returns a number.

(git status -s |select-string -Pattern "^\s*[A|\?|D|M]" -AllMatches).Matches.Count

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBradleyView Question on Stackoverflow
Solution 1 - GitmkarasekView Answer on Stackoverflow
Solution 2 - GitchrisjleeView Answer on Stackoverflow
Solution 3 - GitfwiwView Answer on Stackoverflow
Solution 4 - GittobiwView Answer on Stackoverflow
Solution 5 - GitelectrovirView Answer on Stackoverflow
Solution 6 - GitJean-Bernard JansenView Answer on Stackoverflow
Solution 7 - GitDan FriedmanView Answer on Stackoverflow
Solution 8 - GitMahenderView Answer on Stackoverflow