FDD-book/examples/part-01/ch03-a-gentle-introduction-to-unix/shell-scripting/09-tmp_demo.sh

16 lines
329 B
Bash
Raw Normal View History

#!/bin/sh
# tmp_demo.sh create and clean a temporary file safely
set -eu
tmpfile="$(mktemp -t myscript)"
# Arrange cleanup on exit for success or error
cleanup() {
[ -f "$tmpfile" ] && rm -f "$tmpfile"
}
trap cleanup EXIT
echo "Temporary file is $tmpfile"
echo "Hello temp" > "$tmpfile"
echo "Contents: $(cat "$tmpfile")"