Shell Script mktemp, what's the best method to create temporary named pipe?

tmppipe=$(mktemp -u)
mkfifo -m 600 "$tmppipe"

Unlike regular file creation, which is prone to being hijacked by an existing file or a symbolic link, the creation of a name pipe through mkfifo or the underlying function either creates a new file in the specified place or fails. Something like : >foo is unsafe because if the attacker can predict the output of mktemp then the attacker can create the target file for himself. But mkfifo foo would fail in such a scenario.

If you need full POSIX portability, mkfifo -m 600 /tmp/myfifo is safe against hijacking but prone to a denial of service; without access to a strong random file name generator, you would need to manage retry attempts.

If you don't care for the subtle security problems around temporary files, you can follow a simple rule: create a private directory, and keep everything in there.

tmpdir=
cleanup () {
  trap - EXIT
  if [ -n "$tmpdir" ] ; then rm -rf "$tmpdir"; fi
  if [ -n "$1" ]; then trap - $1; kill -$1 $$; fi
}
tmpdir=$(mktemp -d)
trap 'cleanup' EXIT
trap 'cleanup HUP' HUP
trap 'cleanup TERM' TERM
trap 'cleanup INT' INT
mkfifo "$tmpdir/pipe"

A safer alternative is to use mktemp to create a directory safely, then put your named pipe inside that directory, do an rm -R $dir to get rid of it in the end.


Use the "dry-run" option:

mkfifo $(mktemp -ut pipe.XXX)