Temporary file naming and random numbers

While writing shell scripts, we often need 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...

Perform the following steps to create a temporary file and perform different naming operations on it:

  1. Create a temporary file as follows:
    $ filename=`mktemp`
    $ echo $filename
    /tmp/tmp.8xvhkjF5fH
    

    This will create a temporary file and print its filename which we store in $filename in this example.

  2. To create a temporary directory, use the following commands:
    $ dirname=`mktemp -d`
    $ echo $dirname
    tmp.NI8xzW7VRX
    

    This will create a temporary directory ...

Get Linux Shell Scripting Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.