Check for uncommitted changes in a script
Test for uncommitted changes in a script with git diff --quiet, which exits 1 on a change. Add --cached for staged work, since untracked files never count.
A release script must refuse to run when the working tree is dirty, and it needs an exit status, not output to parse.
git init -q demo && cd demo
git config user.email [email protected]; git config user.name Demo
echo one > a.txt && git add a.txt && git commit -q -m first
git diff --quiet; echo "clean: $?"
echo two >> a.txt
git diff --quiet; echo "modified: $?"
git add a.txt
git diff --quiet; echo "staged, unstaged check: $?"
git diff --cached --quiet; echo "staged check: $?"
git commit -q -m third
touch new.txt
git diff HEAD --quiet; echo "untracked only: $?"clean: 0
modified: 1
staged, unstaged check: 0
staged check: 1
untracked only: 0--quiet implies --exit-code, which makes the command exit 1 when there are differences and 0 when there are none, as the git-diff manual documents. Plain git diff compares the working tree with the index, so a staged change is invisible to it. git diff HEAD --quiet covers both staged and unstaged edits to tracked files.
Untracked files are never part of a diff, so the last check still exits 0 after new.txt appeared on a clean tree. For a complete answer use [ -z "$(git status --porcelain)" ], which lists untracked files as well.