The goal is to get an unambiguous status that can be evaluated in a shell command.
I tried git status
but it always returns 0, even if there are items
Not pretty, but works:
git status | grep -qF 'working directory clean' || echo "DIRTY"
Not sure whether the message is locale dependent, so maybe put a LANG=C
in front.
The return value of git status
just tells you the exit code of git status
, not if there are any modifications to be committed.
If you want a more computer-readable version of the git status
output, try
git status --porcelain
See the description of git status for more information about that.
Sample use (script simply tests if git status --porcelain
gives any output, no parsing needed):
if [ -n "$(git status --porcelain)" ]; then
echo "there are changes";
else
echo "no changes";
fi
Please note that you have to quote the string to test, i.e. the output of git status --porcelain
. For more hints about test constructs, refer to the Advanced Bash Scripting Guide (Section string comparison).
From the git source code there is a sh script which includes the following.
require_clean_work_tree () {
git rev-parse --verify HEAD >/dev/null || exit 1
git update-index -q --ignore-submodules --refresh
err=0
if ! git diff-files --quiet --ignore-submodules
then
echo >&2 "Cannot $1: You have unstaged changes."
err=1
fi
if ! git diff-index --cached --quiet --ignore-submodules HEAD --
then
if [ $err = 0 ]
then
echo >&2 "Cannot $1: Your index contains uncommitted changes."
else
echo >&2 "Additionally, your index contains uncommitted changes."
fi
err=1
fi
if [ $err = 1 ]
then
test -n "$2" && echo >&2 "$2"
exit 1
fi
}
This sniplet shows how its possible to use git diff-files
and git diff-index
to find out if there are any changes to previously known files. It does not however allow you to find out if a new unknown file has been added to the working tree.