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