How to check if Git working tree is dirty

This post goes over the following ways to check if the Git working directory is dirty:

git diff

Check if the working directory is dirty with git diff:

git diff HEAD

This assumes that you don’t care about untracked files.

If files are modified, there will be an output. If the working directory is clean, there will be no output.

conditional statement

Here’s an example of checking with a conditional statement:

if [[ $(git diff --stat) != '' ]]; then
  echo 'dirty'
  echo 'clean'

logical operator

Here’s an example of checking with a logical operator:

git diff --quiet || echo 'dirty'

git status

To check for the presence of untracked files, you’ll need git status:

git status --short

The --short option returns the output in short-format.

For example, if is modified and LICENSE is untracked:

git status -s

Then you can use -z to test that git status -s is null or empty:

[[ -z $(git status -s) ]] || echo 'modified and/or untracked'

Or use -n to test that git status -s is not empty:

[[ -n $(git status -s) ]] || echo 'clean'


There’s also the --porcelain option, which formats the output like --short.

Because it’s a high level command, it could be slow for large repositories. But I was informed that people found it fast and efficient.

Please support this site and join our Discord!