Home > Blockchain >  git run command if nothing to commit
git run command if nothing to commit

Time:03-02

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.

CodePudding user response:

Try something like this:

git diff --exit-code # exit code will be "0" if no changes
if [ $? -gt 0 ]; then
  echo hello
fi

CodePudding user response:

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.

  • Related