Tested in the bash terminal on Linux Ubuntu.
Shell script to programmatically interpret the output of git status
...and tell you if:
- it had an error
- it shows your working tree is clean (no uncommitted changes), or
- it shows your working tree is dirty (you have uncommited changes).
There's a great answer here: Unix & Llinux: Determine if Git working directory is clean from a script. My answer is based on that.
We will use the --porcelain
option with git status
because it is intended to be parsed by scripts!
From man git status
(emphasis added):
--porcelain[=<version>]
Give the output in an easy-to-parse format for scripts. This is similar to the short output, but will remain stable across Git versions and regardless of user configuration. See below for details.
The version
parameter is used to specify the format version. This is optional and defaults to the original version v1 format.
So, do this:
Option 1
if output="$(git status --porcelain)" && [ -z "$output" ]; then
echo "'git status --porcelain' had no errors AND the working directory" \
"is clean."
else
echo "Working directory has UNCOMMITTED CHANGES."
fi
The first part, if output=$(git status --porcelain)
will fail and jump to the else
clause if the git status --porcelain
command has an error. the 2nd part, && [ -z "$output" ]
, tests to see if the output
variable contains an empty (z
ero-length) string. If it does, then the git status
is clean and there are no changes.
Option 2
Generally my preferred usage, however, is to negate the test with -n
(nonzero) instead of -z
(zero) and do it like this:
if output="$(git status --porcelain)" && [ -n "$output" ]; then
echo "'git status --porcelain' had no errors AND the working directory" \
"is dirty (has UNCOMMITTED changes)."
# Commit the changes here
git add -A
git commit -m "AUTOMATICALLY COMMITTING UNCOMMITTED CHANGES"
fi
Option 3
A more-granular way to write the first code block above would be like this:
if ! git_status_output="$(git status --porcelain)"; then
# `git status` had an error
error_code="$?"
echo "'git status' had an error: $error_code"
# exit 1 # (optional)
elif [ -z "$git_status_output" ]; then
# Working directory is clean
echo "Working directory is clean."
else
# Working directory has uncommitted changes.
echo "Working directory has UNCOMMITTED CHANGES."
# exit 2 # (optional)
fi
I've tested all of the above code by copying and pasting the whole blocks into my terminal in a repo in varying states, and it works fine for all 3 conditions:
- your
git status
command is wrong or misspelled
git status
is clean (no uncommitted changes)
git status
is dirty (you have uncommitted changes)
To force the 'git status' had an error
output, simply misspell the --porcelain
option by spelling it as --porcelainn
or something, and you'll see this output at the very end:
'git status' had an error: 0
See also
- My answer here: Get the hash for the current commit, and see if
git status
is "clean" or "dirty"