We can use the following Git commands to check if the working directory is dirty or not:
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.
Here’s an example of checking with a conditional statement:
if [[ $(git diff --stat) != '' ]]; then echo 'dirty' else echo 'clean' fi
Here’s an example of checking with a logical operator:
$ git diff --quiet || echo 'dirty'
To check for the presence of untracked files, you’ll need
$ git status --short
--shortoption 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'
-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
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.