Is there an easy way to calculate number of lines changed in tracked files since last commit? This is about monitoring changes that are not commited yet. Context is that I would like to write a tool that will warn me when I modify large portion of code and haven't commited these changes (facilitate atomic commits). I know I can do git status
or git status --short
and extract modified (and not tracked) files. Then I can use git diff --stat <file>
and loop over files to extract number of changed lines.
Is there any one- or few-liner solution that could do that in bash/zsh or python?
Asked
Active
Viewed 88 times
0
-
Does [this](https://stackoverflow.com/q/18810623/96588) answer your question? – l0b0 May 11 '22 at 10:33
-
@l0b0 - actually yes. One of the answers offer to display diff with zero lines of context and display lines that starts with `+` or `-`. SO the best solution for me would be: `git diff -U0 | grep '^[+-]' | grep -Ev '^(--- a/|\+\+\+ b/)' | wc -l`. Thank you for pointing me to the other question on SO. – izkeros May 11 '22 at 10:47
2 Answers
0
git diff --stat | tail --lines=1
(or -n1
in BSD land) should give you what you want, if I understand correctly:
6 files changed, 726 insertions(+), 6 deletions(-)

l0b0
- 55,365
- 30
- 138
- 223
-1
If you just want to calculate the LOC difference then you can run this command to get the LOCs (reference SO Answer: https://stackoverflow.com/a/4822516/970422)
git ls-files | xargs cat | wc -l
You can run this command on the parent branch and in your local copy to get the difference in LOCs.

Hussain Mansoor
- 2,934
- 2
- 27
- 40
-
This counts the number of **ALL** lines in the git repository, not only changed. – phd May 11 '22 at 15:16
-
My 2nd part after the command mentions this. Run this 2 times and calculate the difference. Run it on your local copy AND run it on the parent branch. Then just get the difference between the two – Hussain Mansoor May 18 '22 at 06:15
-
Please show the two commands. How to run `git ls-files` on the parent branch? [`git ls-files`](https://git-scm.com/docs/git-ls-files) shows information about **files in the index and the working tree**, not on a branch. – phd May 18 '22 at 07:48