This post goes over the following ways to check if the Git working directory is dirty:
Check if the working directory is dirty with
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.
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 informed that people found it fast and efficient.