git diff Command: Detect Changes in CI
git diff reports the differences between commits, the index, and the working tree.
In CI, diff is less about reading patches and more about answering yes-or-no questions: did anything change, which paths changed, and is the tree clean? Its flags make it scriptable.
Common flags
--name-only- list just the changed file paths--name-status- list paths with their status letter (A/M/D)--stat- show a per-file summary of insertions and deletions--exit-code- exit nonzero when there are differences (zero when clean)--quiet- like --exit-code but suppress output<from>..<to>- diff between two commits or branches
Example
# Fail the job if a generated file drifted from source
make generate
if ! git diff --exit-code -- generated/; then
echo "Generated files are stale; run make generate" >&2
exit 1
fiIn CI
git diff --exit-code is the classic check that codegen, formatting, or lockfiles are committed: if the tree changed after running a generator, the job fails. Use --name-only to scope later steps (build only changed packages) and --stat for readable PR summaries.
Using this in CI
CI checkouts are shallow and detached by default, which changes the answer this command gives you. Commands that read history, branch names, or tags need the checkout configured for it.
- uses: actions/checkout@v4
with:
fetch-depth: 0 # history, tags, and git describe all need this
- run: |
git rev-parse --is-shallow-repository # expect false
git rev-parse --abbrev-ref HEAD # prints HEAD when detachedKey takeaways
- git diff --exit-code gates CI on whether generated or formatted files are committed.
- --name-only feeds change-aware steps that act on just the modified paths.
- Compare branches with from..to to scope a diff to a pull request.