brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: diff exits with 0, 1 or 2, and scripts can use that

Diff
~/tips/tip-diff-exit-status-scripts

if ! diff -q /etc/nginx/nginx.conf /srv/backup/nginx.conf > /dev/null; then

Uses diff's exit code to act only when a file really changed.

diff isn’t only for reading. Its exit status tells a script whether two files are the same, which makes it a simple change detector.

if ! diff -q /etc/nginx/nginx.conf /srv/backup/nginx.conf > /dev/null; then
  cp /etc/nginx/nginx.conf /srv/backup/nginx.conf
  echo 'nginx config changed, backup updated'
fi

The codes are 0 when the files are the same, 1 when they differ and 2 when something went wrong, like a missing file or no read permission. Identical files give 0, different ones 1 and a path that doesn’t exist 2.

That third code is the reason I don’t like the simple if ! diff form above for anything important. A missing file also makes it “not equal”, and the script happily acts on it. When it matters, check the code itself:

diff -q a.conf b.conf > /dev/null
case $? in
  0) echo same ;;
  1) echo changed ;;
  *) echo 'diff failed' >&2; exit 1 ;;
esac

If you only need same or not, cmp -s is a bit faster on big files, because it stops at the first difference. It uses the same 0, 1 and 2.

Further reading: diff(1) manual page, GNU diffutils manual

More Diff tips diff -r -x .git -x '*.log' one two diff -y -W 100 old.conf new.conf diff -Naur original/ changed/ > fix.patch patch -p1 --dry-run < ../fix.patch diff --strip-trailing-cr windows.txt unix.txt All Diff tips (12) All topics

Link