Shell scripting (BASH) : How to create temporary random file name

Sometimes you need to create a temporary file in your shell script. There are various methods exist to create a random temporary file name. It is quite useful if your application/shell scripting needs temporary unique file names.

ADVERTISEMENTS

Fig.01: How create a temporary file in linux unix bash/ ksh /zsh shell script

Fig.01: How create a temporary file in linux unix bash/ ksh /zsh shell script

Method # 1 Use of mktemp or tempfile utility

As the name suggest, both of the following commands create a unique temporary file or directory. Just type the mktemp at the shell prompt to create it a temp file or dir:
$ mktemp
Sample outputs

/tmp/tmp.Le4jmo6TrH

OR
$ tempfile
Sample outputs:

/tmp/file1wqzcO

Please note that the tempfile command is deprecated; you should use always use mktemp command instead. So to create a temp file:

tfile=$(mktemp /tmp/foo.XXXXXXXXX)
echo "a file: $tfile"

To create a temp dir:

tdir=$(mktemp -d /tmp/foo.XXXXXXXXX)
echo "a direcotry: $tdir"

How to make a directory

Make a unique temporary directory instead of a file using -d option. The syntax is:
$ mktemp -d

A shell script example

#!/bin/bash
s="https://server1.cyberciti.biz/?Download=ips-v4&Format=text"
f="$(mktemp /tmp/myscript.XXXXXX)"
wget -q -O $f $s
echo "IPv4 address downloaded to '$f'.."
echo "Processing..."
#
# logic to do something on $f here
#
# Delete the temp file
rm -f "$f"

Rest of the following methods are insecure and do not use them in production. They are here for historical reasons only.

Method #2: Use $RANDOM bash shell variable

At shell prompt type the command:
$ echo $RANDOM
Sample outputs:

13354

You can use it as follows:

file="/tmp/myscript.$RANDOM"
echo "Working on temp $file ..."
echo "Deleting $file ..."
rm -f "$file"

Method # 3 Use of $$ variable

This is old and classic method. $$ shell variable returns the current running process this can be use to create unique temporary file as demonstrated in following script:
vi random2.bash

#!/bin/bash
#
TFILE="/tmp/$(basename $0).$$.tmp"
ls > $TFILE
echo "See directory listing in $TFILE"

Save the script and execute as follows:
$ chmod +x random2.bash
$ ./ random2.bash

Use this method if your script needs only ONE temporary file.

🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source & DevOps topics via:
CategoryList of Unix and Linux commands
File Managementcat
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04

ADVERTISEMENTS
14 comments… add one
  • surender Jul 24, 2007 @ 6:03

    how can i record the log in the log file in shell script?
    like during running whatever the user is seeing, that should be recorded in log file.

  • 🐧 nixCraft Jul 24, 2007 @ 7:52
  • Artem Nosulchik Oct 5, 2007 @ 8:17

    createtempfiles.bash is missing… But article is still useful 🙂

  • 🐧 nixCraft Oct 5, 2007 @ 11:10

    Artem,

    Thanks for the heads up! The post has beeb updated.

  • Antti Kaihola Sep 24, 2008 @ 8:25

    $ tempfile -d does not create a temporary directory. Instead, it requires a directory as an argument and creates a temporary file inside that directory.

    • al0 Aug 12, 2015 @ 10:28
      MKTEMP(1)                        User Commands                       MKTEMP(1)
      ...
             -d, --directory
                    create a directory, not a file
      
      So your comment seems to be incorrect.
      To specify directory to create a file in use either
       --tmpdir[=DIR]
                    interpret TEMPLATE relative to DIR.  If DIR is not specified, use $TMPDIR if set, else /tmp.  With this option, TEMPLATE must not be an absolute name.  Unlike with -t, TEM-
                    PLATE may contain slashes, but mktemp creates only the final component.
      or
      -p DIR use DIR as a prefix; implies -t [deprecated]
      
  • tnt2br Oct 30, 2008 @ 18:46

    Thank’s. Obrigado ! Very good tutorial !

  • Anuj Aggarwal Mar 3, 2009 @ 10:27

    Hi

    useful posts.
    But i need to have filenames in sequence eachtime when i run the script in which i am creating the file.

    • CWS Apr 30, 2013 @ 23:09

      This is very necro, but for others who find this rather high ranking search and want to create some “temp” files in sequence, you could do something like:

      BASE=$(mktemp)
      for a in {0..5}; do
      cp $BASE $BASE.$a
      done

      That said, I really don’t understand why you’d care if they were in sequence.

  • Hai Vu May 21, 2009 @ 17:08

    This article is very useful: it helps me solve my problem. Thank you.

  • David Sep 7, 2010 @ 21:49

    After reading http://www.linuxsecurity.com/content/view/115462/151/ , I think some of your examples may be vulnerable to symlink attacks.

    $RANDOM (once in the filename) or $$ alone are not enough because it may be possible for an attacker to create symlinks for all filenames.

  • Yuki Matsukura Sep 12, 2011 @ 11:56

    Great summary. Thank you.
    It helps writing shell script!

  • Wesley Apr 19, 2013 @ 8:15

    mktemp /path/of/dorectory/filename.XXXXXX
    The more X’s you add the more random characters it adds.

  • Hal Sep 24, 2013 @ 21:04

    Suggest that you list the preferred method first rather than last.

Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.