A script that writes to /tmp/rapport.txt ends up creating a problem: another run may already use this name, and a local user may prepare a symbolic link in your place. mktemp creates the file or folder with an unpredictable name and immediately reserves it for the script.
Use a temporary file for intermediate output, then clean it up with trap. This keeps the script’s directory clean even in case of an error or interruption.

Do not create the name with $$
This old habit remains risky:
tmp="/tmp/rapport-$$.txt"
echo "result" > "$tmp"
The PID does not make the name secret and the file is not created at the moment you calculate it. Between constructing the path and writing, another process may occupy this name. mktemp creates the object before returning its path to you.
tmp_file=$(mktemp -p "${TMPDIR:-/tmp}" rapport.XXXXXX) || exit 1
printf '%sn' "result" > "$tmp_file"
The template must contain at least three consecutive X characters in its last component. The characters are replaced upon creation. Always keep quotes around the variable: TMPDIR may contain a space.
Create a temporary directory for multiple files
A temporary directory prevents multiple files from being scattered in /tmp. This is useful for an archive to be prepared, a conversion, or a report that generates intermediate files.
workdir=$(mktemp -d -p "${TMPDIR:-/tmp}" sauvegarde.XXXXXX) || exit 1
printf '%sn' "data" > "$workdir/liste.txt"
tar -czf "$workdir/rapport.tar.gz" "$workdir/liste.txt"
Most systems create this directory with permissions reserved for your account. Check it when the script manipulates a key, an export, or an archive containing sensitive data:
stat -c '%a %U:%G %n' "$workdir"
ls -la "$workdir"
Clean up with trap without deleting a bad path
Define the cleanup function right after creating the directory. Test that the variable exists and that it points to the expected directory before calling rm -rf.
workdir=$(mktemp -d -p "${TMPDIR:-/tmp}" my-script.XXXXXX) || exit 1
cleanup() {
[ -n "${workdir:-}" ] && [ -d "$workdir" ] && rm -rf -- "$workdir"
}
trap cleanup EXIT HUP INT TERM
# script processing here
trap ... EXIT triggers cleanup when the shell exits. The signals HUP, INT, and TERM cover common interruptions. A hard stop with kill -9 does not give the shell time to run this function, so a controlled cleanup must also be planned for large processes.
- create the path with
mktemp, never with a date or$$; - use
mktemp -dif the script produces multiple files; - only delete a variable created and verified by the script;
- keep the temporary file if you need to diagnose a failure, then delete it after analysis.
The guide on Bash history helps to prevent a password given on a command line from remaining in ~/.bash_history. To archive the final result, also refer to creating and extracting a tar archive on Linux.