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.
More on Arguments, I/O, here-docs, process substitution and subshells
How does `getopts` work? Show a complete example.IntermediateWhat is the difference between `getopts` and `getopt`?AdvancedExplain file descriptors 0, 1 and 2 and the main redirection operators.BeginnerWhy is `cmd 2>&1 > file` different from `cmd > file 2>&1`?AdvancedWhat is a here-document, and what is the difference between `<<EOF`, `<<'EOF'` and `<<-EOF`?BeginnerWhat is a here-string (`<<<`)?Intermediate