How to check if a Git working tree is dirty


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

git diff

Check if the working directory is dirty with git diff:

git diff HEAD

This assumes 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

Example of checking with a conditional statement:

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

logical operator

Example of checking with a logical operator:

git diff --quiet || echo 'dirty'

git status

To check for the presence of untracked files, use git status:

git status --short

--short returns the output in short-format.

example

If README.md is modified and LICENSE is untracked:

git status -s
M  README.md
?? LICENSE

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

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

Use -z to test that git status -s is null or empty:

[[ -z $(git status -s) ]] && echo 'clean'

porcelain

--porcelain formats the output like --short:

git status --porcelain

It may be slow for large repositories since it’s a high level command, but others found it fast.



Please support this site and join our Discord!