Skip to content
shellhacks.dev
Git

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.

1 min read
Summarize in AI

A release script must refuse to run when the working tree is dirty, and it needs an exit status, not output to parse.

Shell
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: $?"
Text
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.

Share

More snippets

Git

Show the current branch name

Print the current branch name with git branch --show-current, which prints nothing on a detached HEAD, where rev-parse --abbrev-ref prints the word HEAD.

1 min read
Git

Show the repository root

Print the root of the working tree with git rev-parse --show-toplevel, from any subdirectory, and cd to it in a script that must run from the top.

1 min read
Git

List untracked files only

List untracked files only with git ls-files -o --exclude-standard. Without the second option the output includes every ignored build file as well.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.