0

This question is probably about bash as much as it is about git.

How do I run a command if there is nothing to commit? I did the following, but it runs the echo hello command even if there is nothing to commit:

if git diff --exit-code; then
  echo hello
fi

Coming from a python background, what I assumed would happen is if git ... command is empty then the stuff inside the if statement would not execute. I have confirmed that git diff --exit-code returns nothing.

paulsm4
  • 107,438
  • 16
  • 129
  • 179
sachinruk
  • 8,771
  • 9
  • 45
  • 72

2 Answers2

3

TLDR: Your current code echoes hello in the success case, not the failure case.

We can fix this by inverting the condition, so it becomes:

if ! git diff --exit-code; then
  echo hello
fi

I'd recommend having a look at How to check the exit status using an 'if' statement which provides a few options for how to do this.

Andrew McClement
  • 778
  • 2
  • 11
1

Try something like this:

git diff --exit-code # exit code will be "0" if no changes
if [ $? -gt 0 ]; then
  echo hello
fi
paulsm4
  • 107,438
  • 16
  • 129
  • 179
  • can you put an explanation as to what the stuff in the square brackets mean? Sorry not the best with bash. – sachinruk Mar 02 '22 at 00:11
  • 1
    `$?` is the last exit code. `-gt` is greater than - I think @paulsm4 simply used it to demonstrate an example operation you could do with the exit code. – Andrew McClement Mar 02 '22 at 00:59