Check if Git working tree is dirty


We can use the following Git commands to check if the working directory is dirty or not:

git diff

Use git diff to check if the working directory is dirty:

$ git diff HEAD

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

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

conditional statement

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

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

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 README.md is modified and LICENSE is untracked:

$ git status -s
M  README.md
?? LICENSE

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'

porcelain

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 told that others found it fast and efficient.



If you enjoyed this post, please consider supporting this site!