Check If Files Are Modified or Untracked Using git ls-files
This can be useful if you're writing a script and want to commit changes or do other tasks only if specific files changed.
I had this use case come up recently where I wrote a shell script to help set up preview / ephemeral environments in a Kubernetes cluster.
Long story short this script creates new Kustomize patches but I only wanted to build a new Docker image and run other tasks if this is eiether a brand new environment or a specific file in a git repo was updated.
What this really translates down to is asking a general question of “how can I detect new untracked files in git or if any file changed in a specific directory?”.
Once I knew how to do that, it was a matter of checking if that condition was false and exiting out of the script early.
Fortunately git makes this easy with the git ls-files
command, here’s the
condition:
# This can be an individual file instead of a directory if you want.
path="the/path/to/the/directory/you/want/to/check"
if ! git ls-files --others --modified --error-unmatch "${path}" 2> /dev/null; then
echo "Nothing changed, skipping!"
exit
fi
Here’s a break down of the above command:
--others
detects new untracked files--modified
detects changes to existing files that are tracked--error-unmatch
makes thegit ls-files
command exit with 1 if a match isn’t found2> /dev/null
hides the “path not found” error git throws when using--error-unmatch
You can run git ls-files --help
to see more flags, such as --deleted
and
more.
The video below demos how this works in a git repo.
# Demo Video
Timestamps
- 0:49 – Running the demo script
- 2:15 – Breaking down the git ls-files command
- 5:20 – Making the command fail friendly
- 6:00 – Getting confused by the deleted flag
- 7:05 – Going back to the error flag
Will you be using this in any of your scripts? Let me know below.