Continuing from the comment, in addition to creating the temporary file and setting a trap
to remove the temp file on termination, interrupt or exit, you should validate each step along the way. You should validate mktemp
provides a zero exit code. You should validate that the temp file is in fact created. Then you can use the temp file with confidence that no intervening error took place.
A short example would be:
#!/bin/bash
tmpfile=$(mktemp) ## create temporary file
[ "$?" -eq 0 ] || { ## validate zero exit code from mktemp
printf "error: mktemp had non-zero exit code.
" >&2
exit 1
}
[ -f "$tmpfile" ] || { ## validate temp file actually created
printf "error: tempfile does not exist.
" >&2
exit 1
}
## set trap to remove temp file on termination, interrupt or exit
trap 'rm -f "$tmpfile"' SIGTERM SIGINT EXIT
## Your Script Content Goes Here, below simply exercises the temp file as an example
## fill temp file with heredoc to test
cat > "$tmpfile" << eof
The temporary file was successfully create at: '$tmpfile'.
The temporary file will be removed by a trap function when this
script is terminated or interrupted, or when this script exits
normally.
eof
cat "$tmpfile" ## output temp file to terminal
There are several ways to approach this. This is just a plain-Jane, non-exiting way to put the pieces together and the validations to ensure it all happens as you intend.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…