How can I check in a Bash script if my local Git repository has changes?
There are some scripts that do not work correctly if they check for changes.
I tried it like this:
VN=$(git describe --abbrev=7 HEAD 2>/dev/null)
git update-index -q --refresh
CHANGED=$(git diff-index --name-only HEAD --)
if [ ! -z $CHANGED ];
then VN="$VN-mod"
fi
Is there some kind of boolean check if there has been changes since the last commit, or how can I really test if there are new changes to my local repository?
I'm doing all this for a version creation script (that I found somewhere here).
Solution 1:
Using git status
:
cd /git/directory
if [[ `git status --porcelain` ]]; then
# Changes
else
# No changes
fi
Solution 2:
What you're doing will almost work: you should quote $CHANGED
in case it's empty, and -z
tests for empty, which means no changes. What you meant was:
if [ -n "$CHANGED" ]; then
VN="$VN-mod"
fi
A quote from Git's GIT-VERSION-GEN
:
git update-index -q --refresh
test -z "$(git diff-index --name-only HEAD --)" ||
VN="$VN-dirty"
It looks like you were copying that, but you just forgot that detail of quoting.
Of course, you could also just do this:
if git diff-index --quiet HEAD --; then
# No changes
else
# Changes
fi
Or if you only care about the "something has changed" case:
if ! git diff-index --quiet HEAD --; then
VN="$VN-mod"
fi
Using --quiet
has the benefit that Git can stop processing as soon as it encounters a single diff, so it may not have to check your entire work tree.