I am trying to create a Bash script that knows if there are changes in current working directory. I know that
$ git status
returns a messag
The git-diff man page describes two options of relevance here:
--quiet
Disable all output of the program. Implies --exit-code.
and
--exit-code
Make the program exit with codes similar to diff(1). That is, it
exits with 1 if there were differences and 0 means no differences.
Therefore, a robust approach would be to run
git diff --quiet; nochanges=$?
The shell variable nochanges
will be equal to 0
(i.e. true) if there are no changes, and 1
(i.e. false) otherwise.
You can then use the value of nochanges
in conditional statements as follows:
if [ $nochanges -eq 0 ]; then
# there are no changes
else
# there are changes
fi
Alternatively, if you don't need to store the exit status in a variable, you can do:
if git diff --quiet; then
# there are no changes
else
# there are changes
fi
Edit: Since git diff
is a porcelain Git command and you want to do things programmatically, you should probably use the plumbing Git command called git diff-index
instead (which also has a --quiet
flag, but which must be supplied a tree-ish argument):
if git diff-index --quiet HEAD; then
# there are no changes
else
# there are changes
fi