-
Notifications
You must be signed in to change notification settings - Fork 1
/
overwrite
executable file
·60 lines (50 loc) · 1.35 KB
/
overwrite
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#!/usr/bin/env bash
help() {
cat <<END
Synopsis:
Safely overwrite a file with contents from standard input.
Usage:
$USAGE
Description:
Safely replace the contents of a target file with the entire contents
of standard input. All of standard input is read before overwriting
the target file. Overwrite will fail if standard input is empty.
The copy of standard input is located in $TMPDIR.
Signals HUP, QUIT and TERM are disabled at the start of overwriting
the target file.
This script is derived from an example in the mighty fine book
titled "The Unix Programming Environment" by Rob Pike and Brian
Kernighan.
See:
http://www.amazon.com/Unix-Programming-Environment-Prentice-Hall-Software/dp/013937681X
END
}
PROG=$(basename $0)
USAGE="$PROG [--help] target-file-path"
die()
{
echo "$PROG: ERROR: $@" >&2
echo "usage: $USAGE" >&2
exit 1
}
TMPDIR=${TMPDIR:=/tmp}
NEW=$TMPDIR/$PROG-new.$$
OLD=$TMPDIR/$PROG-old.$$
trap "rm -f $NEW $OLD" EXIT
if [ "$1" = '--help' ]; then
help
exit 0
fi
test $# -ne 1 && die "wrong number of arguments"
FILE=$1
test -e $FILE -a ! -w $FILE && die "can't write to $FILE"
cat >$NEW
STATUS=$?
test $STATUS -eq 0 || die "cat >$NEW non zero: $STATUS: $FILE not overwritten"
test -s $NEW || die "empty input: $FILE not overwritten"
#
# Disable HUP, QUIT and TERM during copy.
#
trap '' 1 2 15
cp $NEW $FILE
exit 0