Daniel Stutzbach Daniel Stutzbach - 11 months ago 54
Git Question

How do I programmatically determine if there are uncommited changes?

In a Makefile, I'd like to perform certain actions if there are uncommited 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
, but I feel like there must be a better way.

Answer Source

"Programmatically" means never ever rely on porcelain commands.
Always rely on plumbing commands.

See also "Checking for a dirty index or untracked files with Git" for alternatives (like git status --porcelain)

You can take inspiration from the new "require_clean_work_tree function" which is written as we speak ;) (early October 2010)

require_clean_work_tree () {
    # Update the index
    git update-index -q --ignore-submodules --refresh

    # Disallow unstaged changes in the working tree
    if ! git diff-files --quiet --ignore-submodules --
        echo >&2 "cannot $1: you have unstaged changes."
        git diff-files --name-status -r --ignore-submodules -- >&2

    # Disallow uncommitted changes in the index
    if ! git diff-index --cached --quiet HEAD --ignore-submodules --
        echo >&2 "cannot $1: your index contains uncommitted changes."
        git diff-index --cached --name-status -r --ignore-submodules HEAD -- >&2

    if [ $err = 1 ]
        echo >&2 "Please commit or stash them."
        exit 1

UPDATE: Daniel Stutzbach points out in the comments that this simple command worked for him:

git diff-index --quiet HEAD --