Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a temporary file with portable shell in a secure way?

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 ?

like image 359
Steve Schnepp Avatar asked Apr 19 '12 09:04

Steve Schnepp


People also ask

How do I create a tmp folder in Linux?

To create new directory use "mkdir" command. For example, to create directory TMP in the current directory issue either "mkdir TMP" or "mkdir ./TMP". It's a good practice to organize files by creating directories and putting files inside of them instead of having all files in one directory.


2 Answers

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} {}')
like image 132
billhill00 Avatar answered Sep 20 '22 06:09

billhill00


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

like image 35
ghoti Avatar answered Sep 22 '22 06:09

ghoti