watch-changes.bash

#333
Raw
Author
Anonymous
Created
Feb. 11, 2021, 5:20 p.m.
Expires
Never
Size
817 bytes
Hits
38
Syntax
Bash
#!/usr/bin/env bash
set -eu -o pipefail

error() {
    printf 'Error: %s\n' "$*"
    usage
}

usage() {
    printf '%s [-n SECONDS] command ...\n' "$0" >&2
    exit $1
}
seconds=2
while getopts 'n:h' options; do
    case "${options}" in
        n)
            seconds="${OPTARG}"
            ;;
        h)
            usage 0
            ;;
        *)
            usage 1
            ;;
    esac
done
shift $((OPTIND - 1))

dir="$(mktemp -d -t watch-changes.XXXXXXXXXXXXXX)"

cleanup() {
  rm -rf "$dir"
}

trap cleanup EXIT

lastf="$dir/last"
currentf="$dir/current"

touch "$lastf"

while :; do
  "$@" &> "$currentf"
  if ! cmp -s -- "$currentf" "$lastf"; then
    printf '================ %s ================\n' "$(date)"
    cat "$currentf"
  fi
  mv "$currentf" "$lastf"
  sleep "$seconds"
done