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 →

git diff Has a Quiet Flag to Halt a Script If a File Was Updated

blog/cards/git-diff-has-a-quiet-flag-to-halt-a-script-if-a-file-was-updated.jpg

This can be really handy if you want to do something specific in a shell script only if a file has been changed in git.

Quick Jump: Demo Video

Recently I wanted to set up this type of workflow in CI:

  • Script A maybe updates a Dockerfile
  • Script B opens a pull request if Script A updated the Dockerfile
  • The CI pipeline will continue to run with or without the Dockerfile being updated

It was important that these scripts were completely decoupled.

I created a little wrapper script to do the above and all I had to do was drop git diff --quiet Dockerfile && exit 0 in between running Script A and Script B. This way the wrapper script will halt and not open the PR if the file didn’t change.

There’s a couple of related flags with git diff:

  • --quiet prevents the diff from showing and exits with 1 if there was a diff, 0 if not
  • --exit-code will exit with 1 if there’s a diff and 0 if not but it’ll show the diff
  • --no-patch will hide the output of the diff

The --quiet flag combines both --exit-code and --no-patch.

By the way I added && exit 0 so that the CI pipeline didn’t fail. I wanted it to continue if the Dockerfile didn’t change. If you didn’t have that requirement you can drop the && exit 0 and let the git diff --quiet Dockerfile command exit with 1 or 0 depending on the result.

Demo Video

Code

If you want to follow along, create a demo.sh file in a directory of your choosing with the contents below:

#!/usr/bin/env bash

set -o errexit
set -o pipefail
set -o nounset

git diff --quiet demo.sh && exit 0

echo "This file has changed, feel free to do whatever you need to do!"

Then run: chmod +x demo.sh && git init && git add -A && git commit -m "Initial commit"

And now you can run ./demo.sh to run the script.

Timestamps

  • 0:20 – Going over the use case of maybe updating a Dockerfile and opening a PR
  • 1:35 – Running the script to see how it works
  • 2:44 – Using && exit 0 to prevent CI from halting
  • 3:35 – Going over a few different related git diff flags

What are you going to diff using this tactic? 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 month (at most), and you can 1-click unsubscribe at any time. See what else you'll get too.



Comments