How do I programmatically determine if there are uncommitted changes?

Viewed 128713

In a Makefile, I'd like to perform certain actions if there are uncommitted changes (either in the working tree or the index). What's the cleanest and most efficient way to do that? A command that exits with a return value of zero in one case and non-zero in the other would suit my purposes.

I can run git status and pipe the output through grep, but I feel like there must be a better way.

11 Answers

Some answers are both overcomplicating the matter and not achieving the desired result. E.g. the accepted answer misses untracked files.

Use the provided git status --porcelain which is designed to be machine parseable despite some people (incorrectly) saying otherwise in the comments. If something shows up in git status, then that's when I consider the working directory dirty. So I test for cleanliness with the test [ -z "$(git status --porcelain=v1 2>/dev/null)" ], which will also pass if run outside a git directory.

Minimum working example:

[ -z "$(git status --porcelain=v1 2>/dev/null)" ] && echo "git undirty"

Anything that shows up in git status (as of now) will trigger this test correctly. The =v1 bit ensures a consistent output format across git versions.


Extra: counting dirty files

Inspired by this answer. You grep the lines of git status --porcelain=v1 output. The first two characters of each line indicate what the status is of the particular file. After grepping, you count how many have that status by piping the output to wc -l which counts the number of lines.

E.g. this script will print some information if run inside a git repository.

#!/bin/sh
GS=$(git status --porcelain=v1 2>/dev/null) # Exit code 128 if not in git directory. Unfortunately this exit code is a bit generic but it should work for most purposes.
if [ $? -ne 128 ]; then
  function _count_git_pattern() {
    echo "$(grep "^$1" <<< $GS | wc -l)" 
  }                                           
  echo "There are $(_count_git_pattern "??") untracked files."                                 
  echo "There are $(_count_git_pattern " M") unstaged, modified files."
  echo "There are $(_count_git_pattern "M ")   staged, modified files."        
fi

I created some handy git aliases to list unstaged and staged files:

git config --global alias.unstaged 'diff --name-only'
git config --global alias.staged 'diff --name-only --cached'

Then you can easily do things like:

[[ -n "$(git unstaged)" ]] && echo unstaged files || echo NO unstaged files
[[ -n "$(git staged)" ]] && echo staged files || echo NO staged files

You can make it more readable by creating a script somewhere on your PATH called git-has:

#!/bin/bash
[[ $(git "$@" | wc -c) -ne 0 ]]

Now the above examples can be simplified to:

git has unstaged && echo unstaged files || echo NO unstaged files
git has staged && echo staged files || echo NO staged files

For completeness here are similar aliases for untracked and ignored files:

git config --global alias.untracked 'ls-files --exclude-standard --others'
git config --global alias.ignored 'ls-files --exclude-standard --others --ignored'

The working tree is "clean" if

git ls-files \
  --deleted \
  --modified \
  --others \
  --exclude-standard \
  -- :/

returns nothing.

Explanation

  • --deleted check for files deleted in the working tree
  • --modified check for files modified in the working tree
  • --others check for files added in the working tree
  • --exclude-standard ignore according to the usual .gitignore, .git/info/exclude ... rules
  • -- :/ pathspec for everything, needed if not running in the root of the repository

That output is empty if the working tree is clean

Tested in the bash terminal on Linux Ubuntu.

Shell script to programmatically interpret the output of git status

...and tell you if:

  1. it had an error
  2. it shows your working tree is clean (no uncommitted changes), or
  3. it shows your working tree is dirty (you have uncommited changes).

There's a great answer here: Unix & Llinux: Determine if Git working directory is clean from a script. My answer is based on that.

We will use the --porcelain option with git status because it is intended to be parsed by scripts!

From man git status (emphasis added):

--porcelain[=<version>]

Give the output in an easy-to-parse format for scripts. This is similar to the short output, but will remain stable across Git versions and regardless of user configuration. See below for details.

The version parameter is used to specify the format version. This is optional and defaults to the original version v1 format.

So, do this:

Option 1

if output="$(git status --porcelain)" && [ -z "$output" ]; then
    # `git status --porcelain` had no errors AND the working directory is clean
    echo "'git status --porcelain' had no errors AND the working directory" \
         "is clean."
else 
    # Working directory has uncommitted changes.
    echo "Working directory has UNCOMMITTED CHANGES."
fi

The first part, if output=$(git status --porcelain) will fail and jump to the else clause if the git status --porcelain command has an error. the 2nd part, && [ -z "$output" ], tests to see if the output variable contains an empty (zero-length) string. If it does, then the git status is clean and there are no changes.

Option 2

Generally my preferred usage, however, is to negate the test with -n (nonzero) instead of -z (zero) and do it like this:

if output="$(git status --porcelain)" && [ -n "$output" ]; then
    echo "'git status --porcelain' had no errors AND the working directory" \
         "is dirty (has UNCOMMITTED changes)."
    # Commit the changes here
    git add -A
    git commit -m "AUTOMATICALLY COMMITTING UNCOMMITTED CHANGES"
fi

Option 3

A more-granular way to write the first code block above would be like this:

if ! git_status_output="$(git status --porcelain)"; then
    # `git status` had an error
    error_code="$?"
    echo "'git status' had an error: $error_code" 
    # exit 1  # (optional)
elif [ -z "$git_status_output" ]; then
    # Working directory is clean
    echo "Working directory is clean."
else
    # Working directory has uncommitted changes.
    echo "Working directory has UNCOMMITTED CHANGES."
    # exit 2  # (optional)
fi

I've tested all of the above code by copying and pasting the whole blocks into my terminal in a repo in varying states, and it works fine for all 3 conditions:

  1. your git status command is wrong or misspelled
  2. git status is clean (no uncommitted changes)
  3. git status is dirty (you have uncommitted changes)

To force the 'git status' had an error output, simply misspell the --porcelain option by spelling it as --porcelainn or something, and you'll see this output at the very end:

'git status' had an error: 0
Related