How to create a temporary file with portable shell

2019-04-07 12: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 ?

3条回答
可以哭但决不认输i
2楼-- · 2019-04-07 12:23

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} {}')
查看更多
做自己的国王
3楼-- · 2019-04-07 12:26

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".

查看更多
来,给爷笑一个
4楼-- · 2019-04-07 12:37

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.$$
查看更多
登录 后发表回答