361

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.

2

12 Answers 12

388

UPDATES:

  • trusktr mentions in the comments of Josh Lee's answer

    Other methods using porcelain assume you're in bash, and that's not cross-shell or cross-platform compatible.
    This one works everywhere:

    git add . && git diff --quiet && git diff --cached --quiet 
    

    seems like it catches every case I need (including untracked files, and git submodules with unstaged modifications which git add . will not stage)

  • the OP Daniel Stutzbach points out in the comments that this simple command git diff-index worked for him:

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

A more precise option would be to test git status --porcelain=v1 2>/dev/null | wc -l, using the porcelain option.
See Myridium's answer.

(nornagon mentions in the comments that, if there are files that have been touched, but whose contents are the same as in the index, you'll need to run git update-index --refresh before git diff-index, otherwise diff-index will incorrectly report that the tree is dirty)

You can then see "How to check if a command succeeded?" if you are using it in a bash script:

git diff-index --quiet HEAD -- || echo "untracked"; // do something about it

Note: as commented by Anthony Sottile

git diff-index HEAD ... will fail on a branch which has no commits (such as a newly initialized repository).
One workaround I've found is git diff-index $(git write-tree) ...

And haridsv points out in the comments that git diff-files on a new file doesn't detect it as a diff.
The safer approach seems to be to run git add on the file spec first and then use git diff-index to see if anything got added to index before running git commit.

git add ${file_args} && \
git diff-index --cached --quiet HEAD || git commit -m '${commit_msg}'

And 6502 reports in the comments:

One problem I bumped in is that git diff-index will tell that there are differences when indeed there is none except for timestamps of the files.
Running git diff once solves the issue (surprisingly enough, git diff does actually change the content of the sandbox, meaning here .git/index)

These timestamp issues can also occur if git is running in docker.


Original answer:

"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
    err=0

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

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

    if [ $err = 1 ]
    then
        echo >&2 "Please commit or stash them."
        exit 1
    fi
}
37
  • 12
    The "plumbing vs. porcelain for scripting" principle is a lesson that Jakub Narębski repeatedly mentioned to me: " How to list all the log for current project in git ? ", " git: changelog day by day ", ...
    – VonC
    Commented Oct 7, 2010 at 6:11
  • 19
    After clicking some of the links you suggest, I found what I was looking for: git diff-index --quiet HEAD. Commented Oct 7, 2010 at 14:46
  • 12
    @DanielStutzbach: That might fail if you have a file called HEAD in the working directory. Better use git diff-index --quiet HEAD --. Commented May 24, 2014 at 17:11
  • 9
    And yet the manual at git status --help states: --porcelain 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.
    – Ed Randall
    Commented May 24, 2016 at 15:13
  • 9
    @VonC that really makes no sense. This way you can twist everything into its reverse. --porcelain gives you the impression it is going to break soon. If it isn't, it should be called plumbing, not porcelain. Using --porcelain causes your script not to break, which renders it NOT a porcelain script ;-). If you wanted your script to break, you shouldn't use --porcelain!!. So it completely incomprehensible this and throws everyone off.
    – Xennex81
    Commented Jul 31, 2016 at 22:30
181

While the other solutions are very thorough, if you want something really quick and dirty, try something like this:

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

It just checks if there is any output in the status summary.

11
  • 18
    works for me. use -n for the inverse (you have changes) e.g. ` if [[ -n $(git status -s) ]]; then ... fi`
    – aaron
    Commented Oct 6, 2012 at 22:35
  • 4
    This is almost right answer, but for script it's better to use --porcelain parameter as shown here Commented Dec 29, 2017 at 21:42
  • 5
    You might want to use git status -s -uall to include untracked files.
    – barfuin
    Commented Feb 15, 2018 at 9:29
  • 4
    @barfuin it looks like git status defaults to all. From git status -h: -u, --untracked-files[=<mode>] show untracked files, optional modes: all, normal, no. (Default: all)
    – calebwoof
    Commented Apr 17, 2020 at 20:27
  • 3
    [ -z "$(git status -s)" ] -- posix & quoted Commented Nov 30, 2021 at 21:06
88

git diff --exit-code will return nonzero if there are any changes; git diff --quiet is the same with no output. Since you want to check for the working tree and the index, use

git diff --quiet && git diff --cached --quiet

Or

git diff --quiet HEAD

Either one will tell you if there are uncommitted changes that are staged or not.

If you want to include untracked files in the test, use git add to stag them first:

git add . && git diff --quiet && git diff --cached --quiet

The git diff --cached --quiet command will catch untracked files that have now been staged with git add .. The git diff --quiet command is still nneeded for catching git submodules with unstaged changes, as git add . will not stage git submodules that have modifications.

When you need to run this check in a cross-platform way, this method is better than most other answers because other answers parse outputs of various other commands (namely git status --porcelain) in a shell-specific way, which means those methods will not work cross-platform. For example, they won't work in Windows PowerShell.

Relying on exit codes will work in a cross-platform way, so the above command using && works pretty much everywhere in macOS, Linux, and Windows. This can be especially useful, for example, for cross-platform NPM scripts in package.json files of JavaScript projects.

6
  • 7
    Those are not equivalent. The single command git diff --quite HEAD will only tell you whether the working tree is clean, not whether the index is clean. For example, if file was changed between HEAD~ and HEAD, then after git reset HEAD~ -- file, it will still exit 0 even though there are staged changes present in the index (wt == HEAD, but index != HEAD). Commented Oct 7, 2010 at 8:03
  • 2
    Warning, this will not catch files removed from the staging area with git rm, AFAICS.
    – nmr
    Commented Apr 2, 2013 at 17:33
  • 31
    New (untracked) files are not detected by git diff --quiet && git diff --cached --quiet . Commented Jun 8, 2015 at 15:37
  • @4LegsDrivenCat how about git add . && git diff --cached --quiet?
    – trusktr
    Commented Oct 30, 2023 at 1:37
  • @nmr how about git add . && git diff --cached --quiet?
    – trusktr
    Commented Oct 30, 2023 at 1:38
34

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

You can use git status --porcelain=v1 and parse the output programatically. The output is empty if there is some uncommitted change, otherwise it is not empty.

A POSIX-compliant minimum working example:

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

If run outside a git repository, this will still say No uncommitted changes.

Details

  • The option --porcelain gives a machine-parseable output.
  • The option specification --porcelain=v1 fixes the output version of the machine-parseable output, so that your script will never break under a future git update. As of my writing, you can check https://git-scm.com/docs/git-status for information about other version options, like --porcelain=v2. You may be able to do more advanced scripting with versions beyond v1.
  • The 2>/dev/null is there so that git status will fail silently, if at all (i.e., if run outside of a git repository).
  • As of this writing, the command git status ... will return exit code 128 if it is not inside a git repository. You can check explicitly for this exit code if you want a third option besides "uncommitted changes" or "no uncommitted changes".

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.

You may code up some more advanced behaviour this way, or pick and choose what you consider qualifies as "uncommitted changes".

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
6
  • @VonC - indeed, I checked the documentation git-scm.com/docs/git-status and noticed the version option. There's a v2 already but it's not default. Also I know other people have already quoted this elsewhere in the comments, but it says of the --porcelain option: "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."
    – Myridium
    Commented Jul 7, 2020 at 6:06
  • Yes, v2 has been introduced in Git 2.11 (github.com/git/git/commit/…), aug. 2016.
    – VonC
    Commented Jul 7, 2020 at 6:15
  • I keep getting zsh: command not found: M in MacOS terminal? Commented Dec 6, 2022 at 12:22
  • @ChuckLeButt I've tested with zsh on MacOS and it works okay for me. What are you putting into the terminal exactly?
    – Myridium
    Commented Dec 14, 2022 at 11:11
  • This gives me the incorrect number of untracked files!
    – jtlz2
    Commented May 15, 2023 at 11:15
34

Expanding on @Nepthar's answer:

if [[ -z $(git status -s) ]]
then
  echo "tree is clean"
else
  echo "tree is dirty, please commit changes before running this"
  exit
fi
2
  • 1
    This is good; I use it to autocommit single files by testing $(git status -s "$file") and then in the else clause git add "$file"; git commit -m "your autocommit process" "$file" Commented Jan 3, 2017 at 14:22
  • 2
    If you make that git status -s an git status --porcelain ; git clean -nd instead, junk directories will be surfaced here too, which are invisible to git status.
    – ecmanaut
    Commented May 28, 2019 at 23:41
11

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

10
  • 1
    It does not see new directories in the working tree
    – ESkri
    Commented Apr 25, 2023 at 8:41
  • 3
    @ESkri that's because git doesn't track directories, it only ever tracks files. Empty directories do not exist as far as Git is concerned
    – CervEd
    Commented Apr 25, 2023 at 9:17
  • Yes, there are no empty directories in the repo (for example, it is impossible to add empty directory to the index). But git does know about empty directories in the working tree. For example, git successfully deletes them with git clean -d.
    – ESkri
    Commented Apr 25, 2023 at 10:03
  • 1
    The working tree is not clean if git clean has something to do in it. Pun intended.
    – ESkri
    Commented Apr 25, 2023 at 10:10
  • 1
    @combinatorist you're probably looking for git diff-index --cached --quiet HEAD -- && true || false
    – CervEd
    Commented Oct 19, 2023 at 9:31
8

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'
6

With python and the GitPython package:

import git
git.Repo(path).is_dirty(untracked_files=True)

Returns True if repository is not clean

3
  • This avoided some of the "timestamp" issues mentioned in other comments
    – Jason
    Commented Nov 27, 2019 at 10:53
  • 2
    Note that GitPython is just using the git CLI as well. If you set LOGLEVEL=DEBUG you will see all the Popen commands it it using to run git diff
    – Jason
    Commented Dec 10, 2019 at 3:34
  • 1
    Assuming the package is well tested, it is more reliable to let package maintainers keep the functions working properly if/when Git changes. GitPython's docs indicate that it may leak resources and that causes me concern.
    – Tim Bender
    Commented Nov 9, 2020 at 19:25
4

As pointed in other answer, as simple as such command is sufficient:

git diff-index --quiet HEAD --

If you omit the last two dashes, the command would fail if you have a file named HEAD.

Example:

#!/bin/bash
set -e
echo -n "Checking if there are uncommited changes... "
trap 'echo -e "\033[0;31mFAILED\033[0m"' ERR
git diff-index --quiet HEAD --
trap - ERR
echo -e "\033[0;32mAll set!\033[0m"

# continue as planned...

Word of caution: this command ignores untracked files.

3
  • 2
    As pointed in comments to that answer, this doesn't detect newly added files
    – minexew
    Commented Jan 22, 2017 at 21:02
  • No, it does detect newly added to index files. Just checked.
    – sanmai
    Commented Jan 24, 2017 at 8:41
  • See question. Untracked files are not changes. git add and git clean to the rescue
    – sanmai
    Commented Jan 24, 2017 at 11:41
1

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
    echo "'git status --porcelain' had no errors AND the working directory" \
         "is clean."
else 
    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

See also

  1. My answer here: Get the hash for the current commit, and see if git status is "clean" or "dirty"
0

Maybe its late but I had similar problem when I want to write to Python script to check working directory and I did this and worked for me.

Warning: this worked only for tracking files.

import subprocess

stash = subprocess.check_output(["git", "stash"], cwd=directory).strip().decode()
if stash != 'No local changes to save':
    print("The working directory is NOT clean")
    subprocess.check_output(["git", "stash", "pop"], cwd=directory)
    exit(1)
-3

Here is the best, cleanest way.

function git_dirty {
    text=$(git status)
    changed_text="Changes to be committed"
    untracked_files="Untracked files"

    dirty=false

    if [[ ${text} = *"$changed_text"* ]];then
        dirty=true
    fi

    if [[ ${text} = *"$untracked_files"* ]];then
        dirty=true
    fi

    echo $dirty
}
2
  • 4
    No, this is not the best. git status is a 'porcelain' command. Don't use porcelain commands in scripts since they can change between git versions. Instead use 'plumbing' commands.
    – spuder
    Commented Jun 21, 2017 at 3:37
  • 3
    I think if you updated it to use git status --porcelain (which is meant for this purpose--a stable format you can parse in a script), possibly also with -z (null-separated instead of newline?) you could do something useful with this idea. @codyc4321 see stackoverflow.com/questions/6976473/… for details
    – msouth
    Commented Sep 27, 2017 at 3:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.