Determining if a directory has changed since the last Git commit
Sometimes it can be useful to determine if a specific directory has changed since the last Git commit.
This can be achieved with the following bash command:
DIRECTORY=mydir
if [[ -z $(git diff HEAD~1 -- $DIRECTORY) ]]; then echo "Directory changed"; else echo "Directory not changed"; fi
This works by running a Git diff between the current HEAD
and the parent commit. If any files in the specified directory have changed then the diff command will return 0
, else it will return 1
.
You can also easily modify this to run logic only if the directory has not changed:
if [[ -z $(git diff HEAD~1 -- $DIRECTORY) ]]; then echo "Directory has not changed"; fi
Or only if the directory has changed:
if [[ $(git diff HEAD~1 -- $DIRECTORY) ]]; then echo "Directory has not changed"; fi
My particular use case was for selectively cancelling CI/CD tests. The CI/CD runner I was using only supported triggers based on files changed between the current master HEAD and the change commit, but I needed to calculate the diff between the current commit and its parent.
Member discussion