O'Reilly logo

Linux Shell Scripting Cookbook by Sarath Lakshman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Temporary file naming and random numbers

While writing shell scripts, we use often require to store temporary data. The most suitable location to store temporary data is /tmp (which will be cleaned out by the system on reboot). We can use two methods to generate standard filenames for temporary data.

How to do it...

tempfile is not seen in non-Debian Linux distributions. The tempfile command comes shipped with Debian-based distributions, such as Ubuntu, Debian, and many more.

The following code will assign a temporary filename to the variable temp_file:

temp_file=$(tempfile)

Use echo $temp_file to print the temporary file name in the terminal.

The output will look similar to /tmp/fileaZWm8Y.

Sometimes we may use a filename with a random number attached ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required