How to get the output of git diff command in Shell Script

Viewed 2668

I am trying to perform Git diff in two branches with the same file. I want to get the difference of two files.

  • If there is a fatal error
  • If there is a difference/ not matched
  • If there is NO difference/ matched

I tried saving the command in a variable to get the result. Example: GIT_DIFF=$(git diff RB_202005:/test.txt RB_202006:/test.txt) and then printing the variable (Example: echo $GIT_DIFF) but nothing is being returned.

2 Answers

Since you are only interested in the cases "no diff", "diff", "error", I would run a

git diff --exit-code --quiet .....

--exit-code sets the exit code in the way the normal diff would do.

--quiet suppresses the output.

If the exit code is 0, you don't have differences.

If the exit code is 1, you have differences.

If the exit code is 2 or 128, you have fatal errors.

UPDATED As the OP pointed out in the comment, git-diff --exit-code produces status code 128, if the file to be compared does not exist. According to the man-page, it should produce the same exit code as the standard diff, which would be 2. Hence it is best to treat any exit code larger than 1 as standard error. This would also catch the case that git itself is not found (in which case the shell would likely report exit code 127).

This would not always work with the new (Git 2.30, Q1 2021) git diff -I, should you want to ignore a diff pattern.

"git diff -I<pattern> -exit-code(man)" should exit with 0 status when all the changes match the ignored pattern, but it didn't.

See commit 50f0439 (16 Dec 2020) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit 59fcf74, 18 Dec 2020)

diff: correct interaction between --exit-code and -I<pattern>

Just like "git diff -w --exit-code"(man) should exit with 0 when ignoring whitespace differences results in no changes shown, if ignoring certain changes with "git diff -I<pattern> --exit-code(man)" result in an empty patch, we should exit with 0.

The test suite did not cover the interaction between "--exit-code" and "-w"; add one while adding a new test for "--exit-code" + "-I".

Related