Interview Prep/Shell Scripting/Arguments, I/O, here-docs, process substitution and subshells

How do you safely create temporary files and directories?

AdvancedConceptArguments, I/O, here-docs, process substitution and subshells
Answer
tmpfile=$(mktemp)                              # /tmp/tmp.XXXXXXXXXX, mode 0600
tmpdir=$(mktemp -d -t deploy.XXXXXX)           # unique dir under $TMPDIR or /tmp
partial=$(mktemp "$dest_dir/.partial.XXXXXX")  # same filesystem as the target
trap 'rm -rf -- "$tmpfile" "$tmpdir"' EXIT

mktemp creates the file atomically with a random name and private permissions. Predictable names like /tmp/backup.$$ let another local user pre-create a symlink and make your root script overwrite /etc/shadow. Create the temp file in the destination directory when you plan to mv it, so the rename is atomic.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arguments, I/O, here-docs, process substitution and subshells