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
You can check if the variable is set by using the -n
expression.
#!/bin/bash
CHANGESTOCOMMIT=$(git status | grep 'Changes to be com')
UNSTAGEDCHANGES=$(git status | grep 'Changes not staged')
# If there are staged changes:
if [ -n "$CHANGESTOCOMMIT" ]; then
echo "Changes need to be committed"
fi
if [ -n "$UNSTAGEDCHANGES" ]; then
echo "Changes made but not staged."
fi
Git tracks changed files that are both staged for committing, and also unstaged files, so your script might want to check both options (or not). The -n
operator checks to see if the variable has been set - if it is empty it will return false.
An alternative is -z
which returns True if it is empty (the logical opposite of -n
. For a full list of conditional expressions please refer to the Bash Reference Manual.