Unix Power ToolsUnix Power ToolsSearch this book

8.17. Picking a Unique Filename Automatically

Shell scripts, aliases, and other programs often need temporary files to hold data to be used later. If the program will be run more than once, or if the temp file needs to stay around after the program is done, you need some way to make a unique filename. Generally these files are stored in /tmp or /usr/tmp.

One way is with the shell's process ID number (Section 24.3), available in the $$ parameter. You might name a file /tmp/myprog$$; the shell will turn that into something like /tmp/myprog1234 or /tmp/myprog28471. If your program needs more than one temporary file, add an informative suffix to the names:

% errs=/tmp/myprog-errs$$
% output=/tmp/myprog-output$$

You can also use date's + option to get a representation of the date suitable for temporary filenames. For example, to output the Year, month, day, Hour, Minute, and Second:

% date
Wed Mar  6 17:04:39 MST 2002
% date +'%Y%m%d%H%M%S'
20020306170515

Use a + parameter and backquotes (``) (Section 28.14) to get a temp file named for the current date and/or time. For instance, on May 31 the following command would store foo.0531 in the Bourne shell variable temp. On December 7, it would store foo.1207:

% temp=foo.`date +'%m%d'`

If you'll be generating a lot of temporary files in close proximity, you can use both the process ID and the date/time:

% output=/tmp/myprog$$.`date +'%Y%m%d%H%M%S'`
% echo $output
/tmp/myprog25297.20020306170222

--JP and DJPH



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.