If you need to write some temporary files that only last as long as your script or application is running, use the directory indicated by the
TMPDIR environment variable, or if that variable is not defined,
/tmp is cleared at boot time on some systems (sometimes it's even in RAM, e.g. by default on Solaris, and on some Linux installations), so it cannot be used for files that must survive a power failure or a reboot.
/var/tmp can be used for files that must survive a reboot, but that may be cleaned by the system administrator from time to time. If your application needs to save files on a permanent basis, write them somewhere in the user's home directory (in
~/.cache/programmingnoobsapp) or under
/tmp is shared between all users, so you need to take precautions when creating a file there. You need to pick a file name that doesn't exist yet, and you need to be careful not to allow a race condition where another process creates the file ahead of you with different permissions, which could be a security hole (if the other process is running as a different user, it could then access and modify your process's data). Use the
mktemp command to create a file in
/var/tmp. By default,
mktemp creates a file in
TMPDIR is unset, which is usually the right place. If you need to use multiple temporary files, or even if you need a single one, I recommend creating a directory for all your temporary files with
mktemp -d and removing it at the end of your script.
trap 'rm -rf "$tmp_root"' EXIT INT TERM HUP