Create a private temp file
Create a private temporary file with mktemp, which gives mode 600 and a random name, and remove it in an EXIT trap even when the script fails.
A script needs scratch space, and a name like /tmp/job.$$ can be guessed or pre-created by another user.
cat > job.sh <<'EOF'
tmp=$(mktemp)
trap 'rm -f -- "$tmp"' EXIT
stat -c 'mode %a, owner %U' "$tmp"
echo "work in progress" > "$tmp"
echo "$tmp" > path.txt
exit 3
EOF
bash job.sh; echo "exit: $?"
[ -e "$(cat path.txt)" ] && echo "file left behind" || echo "file removed by the trap"mode 600, owner root
exit: 3
file removed by the trapmktemp creates the file itself, with exclusive access and mode 600, and prints the unique random name, which closes the race that a predictable name opens for a symlink attack. The command is described in the coreutils manual. The EXIT trap runs when the shell ends for any reason other than SIGKILL, so the file is removed on success, on exit and after most errors.
A trap does not run when the process receives SIGKILL, or when the machine loses power, so a stale file can remain. Use mktemp -d for a directory and remove it with rm -rf, and set TMPDIR to a private directory for more safety. The demo script exits with status 3 on purpose, and the file is still gone afterwards.