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
  • 114,292
  • 17
  • 138
  • 190
sachinruk
  • 9,571
  • 12
  • 55
  • 86

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
  • 1,171
  • 5
  • 14
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
  • 114,292
  • 17
  • 138
  • 190
  • 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