This is a repost with Subject line changed:
It is very sad to see that Brian Kernighan and Rob Pike uses temporary
files in the example. I think the temporary can be easily and better
avoided in this case. The modified version is provided at the end. If you
believe the modified version is not better, I would like to hear it.
I make a lot of effort not to use temporary files in my shell scripts,
I do not know if I am alone in this.
And I do not see the value of saving the the original file in the
script:
cp $file $old # save original file
In "The UNIX Programming Environment", Brian Kernighan and Rob Pike provide
># overwrite: copy standard input to output after EOF
># final version
>opath=$PATH
>PATH=/bin:/usr/bin
>case $# in
>0|1) echo 'Usage: overwrite file cmd [args]' 1>&2; exit 2
>esac
>file=$1; shift
>new=/tmp/overwr1.$$; old=/tmp/overwr2.$$
>trap 'rm -f $new $old; exit 1' 1 2 15 # clean up files
>then
> cp $file $old # save original file
> trap '' 1 2 15 # we are committed; ignore signals
> cp $new $file
>else
> echo "overwrite: $1 failed, $file unchanged" 1>&2
> exit 1
>fi
>rm -f $new $old
# overwrite: copy standard input to output after EOF
# modified version
opath=$PATH
PATH=/bin:/usr/bin
case $# in
0|1) echo 'Usage: overwrite file cmd [args]' 1>&2; exit 2
esac
file=$1; shift
then
trap '' 1 2 15 # we are committed; ignore signals
print -r -- "$new" > $file
else
echo "overwrite: $1 failed, $file unchanged" 1>&2
exit 1
fi