Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Check If Files Are Modified or Untracked Using git ls-files

check-if-files-are-modified-or-untracked-using-git-ls-files.jpg

This can be useful if you're writing a script and want to commit changes or do other tasks only if specific files changed.

Quick Jump:

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 the git ls-files command exit with 1 if a match isn’t found
  • 2> /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.

Never Miss a Tip, Trick or Tutorial

Like you, I'm super protective of my inbox, so don't worry about getting spammed. You can expect a few emails per year (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments