List changed files in a git commit

Sometimes it is necessary to only take action when certain files have changed. This can be achieved with git diff-tree:

# git diff-tree --no-commit-id --name-only -r <COMMIT_SHA> [<PATH_FILTER>]
$ git diff-tree --no-commit-id --name-only -r a3507db9397f5f9fe376e9554ed45bcf6f8c440c
$ git diff-tree --no-commit-id --name-only -r $(git rev-parse --verify HEAD) src/
  • The --no-commit-id suppresses the commit ID output
  • The --name-only argument shows only the file names that were affected. Use --name-status instead, if you want to see what happened to each file (Deleted, Modified, Added)
  • The -r argument is to recurse into sub-trees

Note: git diff-tree does not work with the first commit in a repo.

Here’s an example:

# Create repo
$ mkdir testrepo && cd $_
$ mkdir src
$ git init

# Create test files
$ touch src/{1,2,3}.txt
$ git add src/
$ git commit -m "Initial commit"

# Modify files
$ git rm src/1.txt
$ echo "test" > src/2.txt
$ git mv src/3.txt 3.txt.old
$ git add .
$ git commit -m "Update files"

# Show changes
$ git diff-tree --no-commit-id --name-only -r $(git rev-parse --verify HEAD)
3.txt.old
src/1.txt
src/2.txt
src/3.txt

$ git diff-tree --no-commit-id --name-status -r $(git rev-parse --verify HEAD)
A	3.txt.old
D	src/1.txt
M	src/2.txt
D	src/3.txt

$ git diff-tree --no-commit-id --name-status -r $(git rev-parse --verify HEAD) src/
D	src/1.txt
M	src/2.txt
D	src/3.txt

CI

# GitLab CI
git diff-tree --no-commit-id --name-only -r ${CI_COMMIT_SHA}

# GitHub
git diff-tree --no-commit-id --name-only -r ${{ github.sha }}

To get list of modified files since the last push:

git diff --name-only ${CI_COMMIT_BEFORE_SHA}...${CI_COMMIT_SHA}