226

I have a script which runs rsync with a Git working directory as destination. I want the script to have different behavior depending on if the working directory is clean (no changes to commit), or not. For instance, if the output of git status is as below, I want the script to exit:

git status
Already up-to-date.
# On branch master
nothing to commit (working directory clean)
Everything up-to-date

If the directory is not clean then I would like it to execute some more commands.

How can I check for output like the above in a shell script?

5
  • Would checking a status from last command help here? ($?)
    – UVV
    Commented Sep 11, 2014 at 13:27
  • Could you give more details please? What is the main idea for your script?
    – tachomi
    Commented Sep 11, 2014 at 13:29
  • @tachomi I added the context in the edit Commented Sep 11, 2014 at 13:53
  • you could just assume it's not clean and do a git reset --hard origin/branch if that is what you are going for... like if you are trying to cleanup after compiling something, etc.
    – SnakeDoc
    Commented Sep 11, 2014 at 16:42
  • 2
    @SnakeDoc You could, but I assume that the inverse case would be more common, i.e. exit if the working directory is dirty to avoid mangling local changes. Considering both case would make question more useful for future readers. Commented Sep 11, 2014 at 16:54

7 Answers 7

329

Parsing the output of git status is a bad idea because the output is intended to be human readable, not machine-readable. There's no guarantee that the output will remain the same in future versions of Git or in differently configured environments.

UVVs comment is on the right track, but unfortunately the return code of git status doesn't change when there are uncommitted changes. It does, however, provide the --porcelain option, which causes the output of git status --porcelain to be formatted in an easy-to-parse format for scripts, and will remain stable across Git versions and regardless of user configuration.

We can use empty output of git status --porcelain as an indicator that there are no changes to be committed:

if [ -z "$(git status --porcelain)" ]; then 
  # Working directory clean
else 
  # Uncommitted changes
fi

If we do not care about untracked files in the working directory, we can use the --untracked-files=no option to disregard those:

if [ -z "$(git status --untracked-files=no --porcelain)" ]; then 
  # Working directory clean excluding untracked files
else 
  # Uncommitted changes in tracked files
fi

To make this more robust against conditions which actually cause git status to fail without output to stdout, we can refine the check to:

if output=$(git status --porcelain) && [ -z "$output" ]; then
  # Working directory clean
else 
  # Uncommitted changes
fi

It's also worth noting that, although git status does not give meaningful exit code when the working directory is unclean, git diff provides the --exit-code option, which makes it behave similar to the diff utility, that is, exiting with status 1 when there were differences and 0 when none were found.

Using this, we can check for unstaged changes with:

git diff --exit-code

and staged, but not committed changes with:

git diff --cached --exit-code

Although git diff can report on untracked files in submodules via appropriate arguments to --ignore-submodules, unfortunately it seems that there is no way to have it report on untracked files in the actual working directory. If untracked files in the working directory are relevant, git status --porcelain is probably the best bet.

9
  • 13
    ughhh git status --porcelain will exit with code 0 even if there are changes not staged for commit and untracked files. Commented Aug 31, 2018 at 21:19
  • 1
    I was interested in determining ahead of time if git stash would do anything (it doesn't output a useful return code). I had to add --ignore-submodules as otherwise git status would indicate submodule changes which git stash ignores.
    – Devin Lane
    Commented Oct 27, 2018 at 21:03
  • 7
    @AlexanderMills: I observed the same. But then checked what if [ -z was doing. The -z means that if the following string is empty, the if evaluates to true. In other words, if this git status --porcelain results in no string, the repo is clean. If not, it lists the modified/added/removed files and is no longer an empty string. The if then evaluates to false.
    – Adeynack
    Commented May 17, 2019 at 12:36
  • 7
    Use git diff --quiet --exit-code if you just want the exit code
    – kigawas
    Commented Jul 2, 2020 at 3:09
  • 3
    I find git diff --quiet (which per the man page also implies --exit-code) returns 256 if there are changes, 33024 if not in a git tree, and various other high numbers for different error conditions. I wonder if the value 256 can be relied upon through different versions of git?
    – Rodney
    Commented Jun 2, 2021 at 13:23
57

Use:

git update-index --really-refresh
git diff-index --quiet HEAD

The return code reflects the state of the working directory (0 = clean, 1 = dirty). Untracked files are ignored.

7
  • 21
    Returns 0 when there are untracked files in the current directory. Commented Apr 12, 2018 at 1:48
  • 6
    If files had been touched/overwritten but are otherwise identical to the index, you need to first run git update-index --refresh before git diff-index HEAD. More info: stackoverflow.com/q/34807971/1407170
    – sffc
    Commented Nov 1, 2018 at 2:28
  • 1
    @AdamParkin I just add all files with git add . before issuing it. Usually it's the way to use it in a script
    – ceztko
    Commented Dec 7, 2018 at 13:27
  • 1
    This is great. Note that a return/exit code of non-zero is also interpreted as an 'error', which if you're in a script with set -e then your script will exit if 'dirty'. This can be avoided by doing set +e before the call to git, and adding set -e again after you've evaluated $?. Commented Mar 29, 2019 at 16:00
  • 1
    @orionelenzil a better option than using set +e is to put to use the 2nd sentence in the doc you linked to. You even used it in your answer Commented Jul 13, 2022 at 22:37
6

Minor extension to André's excellent answer.

Untracked files are ignored.

git update-index --really-refresh
if git diff-index --quiet HEAD
then
  GIT_MODS="clean"
else
  GIT_MODS="dirty"
fi

If you want to avoid putting stuff in stdout, you may want to add >> /dev/null or similar on the update-index line.

2
  • 5
    Accessing $? is inferior to just using if directly on the command: if ! git diff-index --quiet HEAD; then. However, this method is not 100% reliable, suffering from a potential false-positive "dirty" result if you don't first run git update-index --really-refresh. To see this in action touch an existing committed file to update only its date, and then you'll see a non-zero return code from diff-index even though there are actually no changes.
    – ErikE
    Commented Jul 13, 2020 at 4:19
  • I get the diff-index, but exactly what is update-index need for?
    – lindhe
    Commented Jul 27, 2023 at 14:50
5

If you just want a 0 or 1 process exit code, then you can just run a test outside of an if-then block.

#!/bin/bash

[ -z "$(git status --porcelain)" ]

or

#!/bin/bash

test -z "$(git status --porcelain)"

Example:

$ test -z "$(git status --porcelain)"
$ echo $?
0

$ echo 'hello world' > fish.txt
$ test -z "$(git status --porcelain)"
$ echo $?
1
0

I made this kind of test

TEST=$(git status --porcelain|wc -l)
if [ 0 -eq $TEST ]; then
   echo "No changes"
else
   echo "Changes"
fi 
1
  • 2
    There is no need to count the number of lines, just to determine if any lines were produced, so piping to another program is wasteful and doesn't express intent well. Please see Thomas Nyman's answer for a better solution.
    – ErikE
    Commented Jul 13, 2020 at 4:11
0

How about using git describe --broken --dirty --all and checking the result to see if it ends in -dirty (or -broken); then, using the same thing on any submodules with git submodule foreach ... ?

This requires a modern (version >= 3.x) of bash as I understand it, it also does not investigate untracked files - which is not unreasonable in my opinion (at least they shouldn't be clobbered if a difference branch is checked out!) - note that it only returns a zero exit status if everything is clean:

#!/bin/bash

RESULT=$(git describe --broken --dirty --all)
STATUS="clean"
if [[ "${RESULT}" =~ broken$ ]]; then
    # Bail out now, in case it is not safe to look for sub-modules
    echo "Main repository is broken."
    exit -3
elif [[ "${RESULT}" =~ dirty$ ]]; then
    echo "Main repository is dirty - not checking any submodules."
    STATUS="dirty"
    exit -1
else
    git submodule foreach --recursive --quiet 'RESULT=$(git describe --broken --dirty --all) 
        if [[ "${RESULT}" =~ broken$ ]]; then
            echo "Submodule ${name} is broken."
            exit -3
        elif [[ "${RESULT}" =~ dirty$ ]]; then
            echo "Submodule ${name} is dirty."
            STATUS="dirty"
        else
            echo "Submodule ${name} is clean."
        fi' 
    echo -n "Main repository is clean "
    if [ "${STATUS}" = "dirty" ]; then
        echo "- but at least one submodule is dirty."
        exit -2
    else
        echo "- and so are any submodules."
    fi
fi
exit 0
0

git status --short can be used for that. It prints list of modified or untracked files without clutter. Empty output means no changes.

if [ -z "$(git status --short)" ]; then
  echo "Clean"
else
  echo "Dirty"
fi

Output is almost identical (if not identical) like in git status --porcelain suggested in other answers, but --short is more straightforward and easier to remember. On the other hand, --porcelain API will keep its behavior across Git versions and configurations (see docs) which is an important factor, too.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .