13

I want to create a temporary file in POSIX shell (/bin/sh).

I found out that mktemp(1) doens't exist on my AIX box, and according to How portable is mktemp(1)?, it isn't that portable and/or secure anyway.

So, what should I use instead ?

Community
  • 1
  • 1
Steve Schnepp
  • 4,620
  • 5
  • 39
  • 54

3 Answers3

14

Why not use /dev/random?

It could be neater with perl but od and awk will do, something like:

tempfile=XXX-$(od -N4 -tu /dev/random | awk 'NR==1 {print $2} {}')
Steve Schnepp
  • 4,620
  • 5
  • 39
  • 54
billhill00
  • 166
  • 1
  • 3
  • That's _exactly_ what i was looking for (secure & POSIX). Didn't think about `/dev/random`, but it feels so obvious once said :) – Steve Schnepp Apr 23 '12 at 11:32
  • For almost all purposes /dev/urandom is preferable. See https://unix.stackexchange.com/a/324210/197479. Using hex is shorter. Tested this on AIX6.1: tempfile=XXX-$(od -N4 -tx /dev/urandom | awk 'NR==1 {print $2} {}') – Ted Jan 23 '18 at 16:05
  • 3
    The pipe to `awk` can be avoided altogether as `-An` is portable: `tempfile=$(od -An -N4 -tx /dev/urandom); tempfile=XXX-${tempfile## }` – Adrian Günter Apr 17 '18 at 19:08
  • 1
    Also, to convert an arbitrary number of bytes one can do: `length=7; tempfile=XXX-$(od -An -N${LENGTH} -tx1 /dev/urandom | tr -d ' ')` – Adrian Günter Apr 17 '18 at 19:19
  • I don't think /dev/random is specified by POSIX. – Tripp Kinetics Oct 25 '18 at 19:03
  • You can also use regular expressions to retrieve just the hexa digits: `[[ $rnd =~ ([[:xdigit:]]+) ]] && rnd=${BASH_REMATCH[1]}` – Roland Mar 06 '20 at 13:20
  • `tempfile=$(od -An -N4 -tx /dev/urandom | tr -C -d '[:xdigit:]')` remove all except hex digits. – Roland Mar 06 '20 at 13:42
3

You didn't exactly define "secure", but one element of it is probably to clean up after yourself.

trap "rm -f \"$tmpfile\"" 0 1 2 3 15

You can probably man 3 signal to see if there are other signals that should cause your temp file to be erased. Signal zero means "on a clean exit".

nwk
  • 4,004
  • 1
  • 21
  • 22
ghoti
  • 45,319
  • 8
  • 65
  • 104
1

Got here from google for portable mktemp. My needs are less secure than OP's, so I ended up just using the script's PID:

tempx=/tmp/mytemp.$$
Steve Goranson
  • 329
  • 2
  • 8