The whole point of mktemp
is, to quote its manual, to “create a temporary file or directory, safely”. Basically, in a script, you can write
file="$(mktemp)"
or
dir="$(mktemp -d)"
and use either as you wish, safe in the knowledge that the temporary file and directory are accessible only by the user running the command (and root, of course, in most setups), and that they aren’t a symlink to something else, etc. (There are still some caveats; in particular, you need to check the exit status, and the parent directory needs to be safe to use. See the documentation for details.)
mktemp -u
doesn’t give these guarantees, because it separates the construction of the file name from its use; in a script, you’d have to run (don’t do this)
dir="$(mktemp -u)"
mkdir "$dir"
chmod 700 "$dir"
In between mktemp
and mkdir
, another process can create the directory, with different ownership; or, in the case of a file, another process can create the file or create a symlink in its place...
mktemp
without-u
is particularly safe, either, at least when creating temp files, not dirs. The temp file could've been accidentally deleted since it was created until it was first used, and then we're back where we started from -- opportunity for symlink attack. If you're using any shell with here-strings (bash, ksh, zsh) on Linux, this will create a temp file with two separate handles (7 for read, 8 for write) to it, which will be completely managed by the shell (you don't have to remove it or care about its path, etc):exec 7<<<'' 8>/dev/fd/7
. – Sep 09 '19 at 01:35bash-5.0
. Apparently, it's the effect of a fix for this bug. Sad. – Oct 26 '19 at 00:37mktemp(1)
andrm
. – Oct 26 '19 at 00:40head -n 6000
may have to be adjusted):while ! rm /tmp/sh-thd* 2>/dev/null; do : ; done & (printf "cat <<foo >/dev/null\n"; yes line | head -n6000; printf "foo") | bash; kill $!
– Oct 30 '19 at 09:17