my recent reads..

Atomic Accidents: A History of Nuclear Meltdowns and Disasters; From the Ozark Mountains to Fukushima
Power Sources and Supplies: World Class Designs
Red Storm Rising
Locked On
Analog Circuits Cookbook
The Teeth Of The Tiger
Sharpe's Gold
Without Remorse
Practical Oscillator Handbook
Red Rabbit

Wednesday, January 17, 2007

Generating a temp filename in Bash

Here's a function that simplifies the process of generating temporary filenames in shell scripts (I use bash). This function will generate a temporary filename given optional path and filename prefix parameters. If the file happens to already exist (a small chance), it recurses to try a new filename.

It doesn't cleanup temp files or anything fancy like that, but it does have the behaviour that if you never write to the temp file, it is not created. If you don't like that idea, touch the file before returning the name.

This procedure demonstrates the use of variable expansion modifiers to parse the parameters, and the $RANDOM builtin variable.

function gettmpfile()
{
local tmppath=${1:-/tmp}
local tmpfile=$2${2:+-}
tmpfile=$tmppath/$tmpfile$RANDOM$RANDOM.tmp
if [ -e $tmpfile ]
then
# if file already exists, recurse and try again
tmpfile=$(gettmpfile $1 $2)
fi
echo $tmpfile
}

By default (with no parameters specified), this function will return a random filename in the /tmp directory:

[prompt]$ echo $(gettmpfile)
/tmp/324003570.tmp


If you specify a path and filename prefix, these are used to generate the name:
[prompt]$ echo $(gettmpfile /my_tmp_path app-tmpfile)
/my_tmp_path/app-tmpfile-276051579.tmp

4 comments:

Anonymous said...

man tempfile

FILE=$(tempfile)

Unknown said...

Thanks "anonymous". That made me check again for built-in support!

Haven't tracked down exactly which *nix's have a tempfile command. I've got RHEL 3 in front of me right now, and it doesn't have tempfile .... but it does have a mktemp command which does the job (says it appread in OpenBSD 2.1)

Anyway, I preserve my posting then as mainly a demonstration of variable expansion and substitution in bash!

Unknown said...

Thanks for this! It helped me find mktemp.

Unknown said...

glad I provided a roundabout way to some useful info, Mike;) for completeness, here's a
mktemp man page.