Reputation: 4680
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 ?
Upvotes: 13
Views: 3838
Reputation: 3677
Similar to Steve's answer, I don't need high security, but do need to create multiple unique files in a script. Initially I simply used $RANDOM
, but this does not appear to be very portable either, so I used /dev/urandom instead:
rand="$(LC_ALL=C tr -dc 'a-zA-Z0-9' < /dev/urandom | head -c 10)"
tmp="${TMPDIR}custmp.$rand"
Note that mktemp also creates the file and sets the access mode 0600, so you could do the following:
rand="$(LC_ALL=C tr -dc 'a-zA-Z0-9' < /dev/urandom | head -c 10)"
local tmpFile="${TMPDIR}customtmp.$rand"
touch "$tmpFile"
chmod 0600 "$tmpFile"
And while I'm at it, here's a mktemp -d
equivalent:
rand="$(LC_ALL=C tr -dc 'a-zA-Z0-9' < /dev/urandom | head -c 10)"
local tmpDir="${TMPDIR}customtmpdir.$rand"
mkdir -m 0700 "$tmpDir"
Note the temp dir requires rwx rights for the owner (mktemp -d
also does this) otherwise you can't navigate into it.
Upvotes: 0
Reputation: 329
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.$$
Upvotes: 1
Reputation: 46816
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".
Upvotes: 4
Reputation: 166
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} {}')
Upvotes: 14