How can I programmatically (in a shell script) determine whether or not there are changes?

0

Issue

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 message like “nothing to commit”. What I am trying to, is to define a variable to true or false. This boolean value will tell me if there are or not changes.

Obviously I am not an expert of bash scripts. I tried something like this,

there_are_changes=$(git status | grep nothin)
echo $there_are_changes

but it doesn’t work as expected. What should I do?

Solution

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

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

As pointed out in a comment below, the approach outlined above does not cover untracked files. To cover them as well, you can use the following instead:

if [ -z "$(git status --porcelain)" ]; then
    # there are no changes
else
    # there are changes
fi

Answered By – jub0bs

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More