/ mkifdiff
mkifdiff
 1  #!/usr/bin/env bash
 2  set -euo pipefail
 3  #
 4  #  replace file with stdin only if content different than file
 5  #  used in `make`. keep timestamps older unless there's a change
 6  #
 7  #  20191024WF  init
 8  #  20230718WF  add NOEMPTY (-n or --noempty)
 9  
10  # need a file and needs to be in a pipe
11  tty >/dev/null  && echo "need to pipe to $0; cmd | $0 output.txt" && exit 1
12  usage(){ echo "USAGE: cmd | $0 [-n|--noempty] output.txt"; }
13  [ $# -eq 0 -o $# -gt 2 ] && usage >&2 && exit 1
14  [ "$1" == "-h" ] && usage && exit 0
15  
16  # might want to avoid overwritting with an empty file
17  NOEMPTY=
18  [ "$1" = "--noempty" -o "$1" = "-n" ] && NOEMPTY=1 && shift;
19  
20  # temporary file for diffing
21  TMPFILE=$(mktemp "/tmp/XXXXX-$(basename "$0").lst")
22  # dont leave tempfiles all over the place
23  trap '[ -n "$TMPFILE" -a -r "$TMPFILE" ] && rm $TMPFILE' EXIT
24  
25  # when file doesn't exist. there's nothing to diff. so just write it
26  if [ ! -e "$1" ]; then
27     cat > "$1"
28     echo "$1 did not previously exist. nothing for $0 to diff. creating '$1'"
29     exit 0
30  fi
31  # put pipe into a file
32  cat > "$TMPFILE"
33  if [ ! -s "$TMPFILE" ]; then
34     warn "# WARNING: empty output directed to '$1'!"
35     [ -n "$NOEMPTY" ] &&
36        warn "# remove -n/--noempty to continue" &&  exit 1
37  fi
38  
39  # update input only if pipe output was different
40  ! diff -q "$TMPFILE" "$1" 2>&1 >/dev/null &&
41     mv "$TMPFILE" "$1" ||
42     echo "$1 has not changed"