175

Are there objectively better ways to create temporary files in bash scripts?

I normally just name them whatever comes to my mind, such as tempfile-123, since it will be deleted when the script is over. Is there any disadvantage in doing this other than overwriting a possible tempfile-123 in current folder? Or is there any advantage in creating a temporary file in a more careful way?

Zoran Pavlovic
  • 1,166
  • 2
  • 23
  • 38
Strapakowsky
  • 2,313
  • 2
  • 16
  • 17
  • 1
    Don't use temporally files. Use temporally directories instead. And don't use mktemp. See here why: http://www.codeproject.com/Articles/15956/Security-Tips-for-Temporary-File-Usage-in-Applicat – ceving Jun 11 '12 at 15:28
  • 25
    @ceving That article is simply wrong, at least when applied to the shell command mktemp (as opposed to the mktemp library call). As mktemp creates the file itself with a restrictive umask, the attack given only works if the attacker is operating under the same account as the attackee... in which case the game is already lost. For best practices in the shell-scripting world, see http://mywiki.wooledge.org/BashFAQ/062 – Charles Duffy Jun 11 '12 at 15:34
  • You can also use `tempfile(1)` on systems that have it. – Dennis Williamson Jun 11 '12 at 16:38
  • hi @CharlesDuffy. I'd love to make your answer the default - such an excellent resource! Thank you! – Steven Dake May 14 '23 at 23:30

7 Answers7

202

The mktemp(1) man page explains it fairly well:

Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win. A safer, though still inferior, approach is to make a temporary directory using the same naming scheme. While this does allow one to guarantee that a temporary file will not be subverted, it still allows a simple denial of service attack. For these reasons it is suggested that mktemp be used instead.

In a script, I invoke mktemp something like

mydir=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")

which creates a temporary directory I can work in, and in which I can safely name the actual files something readable and useful.

mktemp is not standard, but it does exist on many platforms. The "X"s will generally get converted into some randomness, and more will probably be more random; however, some systems (busybox ash, for one) limit this randomness more significantly than others


By the way, safe creation of temporary files is important for more than just shell scripting. That's why python has tempfile, perl has File::Temp, ruby has Tempfile, etc…

Will Barnwell
  • 4,049
  • 21
  • 34
kojiro
  • 74,557
  • 19
  • 143
  • 201
  • 2
    The -t option is deprecated: http://www.gnu.org/software/coreutils/manual/html_node/mktemp-invocation.html – Tibor Vass May 09 '14 at 23:42
  • 7
    It seems the most safe and most cross-platform way to use `mktemp` is in combination with `basename`, like so `mktemp -dt "$(basename $0). XXXXXXXXXX"`. If used without `basename` you might get an error like this _mktemp: invalid template, `/tmp/MOB-SAN-JOB1-183-ScriptBuildTask-7300464891856663368.sh.XXXXXXXXXX', contains directory separator_. – i4niac May 28 '14 at 01:55
  • 7
    Ignore they typo (extra space). `mktemp -dt "$(basename $0).XXXXXXXXXX"` is the correct way. – i4niac May 28 '14 at 02:06
  • 4
    @i4niac: you **need** to quote that `$0`, there are spaces a plenty in the land of OS X. `mktemp -dt "$(basename "$0").XXXXXX"` – Orwellophile May 18 '15 at 13:08
  • @Orwellophile, true, just ran a little experiment to confirm. I just got used to the fact that I only use this construction in the scripts I develop and I know where and how those are called. But again, your point is absolutely correct, you never know who will be using your script in some strange way. P.S. spaces are evil. – i4niac May 19 '15 at 14:22
  • I'm using it on OS X now, with a teency addition to double check i'm not about to screw the pooch: `function mktmp { TEMPDIR=$( mktemp -dt "$(basename -- "$0").$$.XXXX" ) touch "$TEMPDIR"/.tmpdir }` *e.g.,* `mktmp && rsync -r root@internet:/ "$TEMPDIR/"` *excuse the ironic but non-clashing var/fn names. – Orwellophile Jun 01 '15 at 16:53
  • On Ubuntu 14.04 you commands gives the error `mktemp: too few X's in template ‘bash’`. – Tor Klingberg Jul 29 '15 at 10:39
  • @TorKlingberg That is addressed in the post as well as multiple comments. – kojiro Jul 29 '15 at 14:35
  • 13
    Also it may be nice to remove the tempdir at the end of the script execution: `trap "rm -rf $mydir" EXIT` – KumZ Jul 25 '16 at 12:33
  • On many linux systems you can create these temp files in the tmpfs `/run/user/$(id -u)` which has 700 permissions by default on my system. This creates the tempfile in RAM rather than on disk. Of course you might have /tmp mounted as a tmpfs anyway but I believe /run/user/ would be more portable. – Jesse the Wind Wanderer Aug 07 '16 at 04:55
51

Yes, use mktemp.

It will create a temporary file inside a folder that is designed for storing temporary files, and it will guarantee you a unique name. It outputs the name of that file:

> mktemp
/tmp/tmp.xx4mM3ePQY
>
Paul
  • 139,544
  • 27
  • 275
  • 264
19

You might want to look at mktemp

The mktemp utility takes the given filename template and overwrites a portion of it to create a unique filename. The template may be any filename with some number of 'Xs' appended to it, for example /tmp/tfile.XXXXXXXXXX. The trailing 'Xs' are replaced with a combination of the current process number and random letters.

For more details: man mktemp

John Lawrence
  • 2,923
  • 17
  • 23
12

Is there any advantage in creating a temporary file in a more careful way

The temporary files are usually created in the temporary directory (such as /tmp) where all other users and processes has read and write access (any other script can create the new files there). Therefore the script should be careful about creating the files such as using with the right permissions (e.g. read only for the owner, see: help umask) and filename should be be not easily guessed (ideally random). Otherwise if the filenames aren't unique, it can create conflict with the same script ran multiple times (e.g. race condition) or some attacker could either hijack some sensitive information (e.g. when permissions are too open and filename is easy to guess) or create/replacing the file with their own version of the code (like replacing the commands or SQL queries depending on what is being stored).


You could use the following approach to create the temporary directory:

TMPDIR=".${0##*/}-$$" && mkdir -v "$TMPDIR"

or temporary file:

TMPFILE=".${0##*/}-$$" && touch "$TMPFILE"

However it is still predictable and not considered safe.

As per man mktemp, we can read:

Traditionally, many shell scripts take the name of the program with the pid as a suffix and use that as a temporary file name. This kind of naming scheme is predictable and the race condition it creates is easy for an attacker to win.

So to be safe, it is recommended to use mktemp command to create unique temporary file or directory (-d).

kenorb
  • 155,785
  • 88
  • 678
  • 743
  • 3
    It does improve the answer indeed. My upvote was already yours, though. Can't vote more. One suggestion I have is to explain what `${0##*/}` and `$$` expand to, or link to some documentation about it. – jpbochi Nov 14 '17 at 14:31
  • @jpbochi `${0##*/}` is the file name of the script that is currently running and `$$` is its process id. Generally, I don't think this solution is a good approach because it can leave hidden files and folders in various directories the script is being executed from. The temporary files and folders can be deleted afterward, but if the script is halted (using `CTRL-C`), then the they will remain. It's better practice to use `mktemp` because it creates temporary files in the system's temporary folder. – Dave F Jan 24 '22 at 00:59
8

mktemp is probably the most versatile, especially if you plan to work with the file for a while.

You can also use a process substitution operator <() if you only need the file temporarily as input to another command, e.g.:

$ diff <(echo hello world) <(echo foo bar)
Barry Jones
  • 1,329
  • 1
  • 9
  • 16
3

To somewhat expand on previous answers here, you want to run mktemp and make sure you also clean up afterwards. The usual way to do that is with trap, which lets you set up a hook that can be run when your script is interrupted.

Bash also provides the EXIT pseudo-signal so that you can set up a trap to be run when your script exits successfully, and ERR which triggers if your script produces an error. (See also What does set -e mean in a bash script? for some unobvious consequences.)

t=$(mktemp -d -p temporary.XXXXXXXXXXXX) || exit
trap 'rm -rf "$t"; exit' ERR EXIT  # HUP INT TERM

: # use "$t" to your heart's content ...

You might want to set up additional signals besides ERR and EXIT; obviously, kill -9 cannot be trapped (which is why it should not be used, except in emergencies). HUP (signal 1) and INT (signal 2) are generated when your script's session is hung up, or the user presses ctrl-C, respectively. TERM (signal 15) is the default signal sent by kill, and requests the script to be terminated.

mktemp -p replaces mktemp -t which is regarded as obsolete. The -d option says to create a directory; if you only need a single temporary file, obviously, that's not necessary.

tripleee
  • 175,061
  • 34
  • 275
  • 318
1

The mktemp docs have some nice examples.

If you require a certain suffix (file extension) for your temporary file. You can do the following

$ myfile=$(mktemp --suffix ".txt")
$ echo "$myfile"
/tmp/tmp.9T9soL2QNp.txt

If you don't want the file to be created, but just want a name, you can additionally use the -u/--dry-run flag.

$ myfile=$(mktemp -u --suffix ".txt")
$ echo "$myfile"
/tmp/tmp.Y8cMDJ1DDr.txt

BUT NOTE, when using -u/--dry-run

Using the output of this command to create a new file is inherently unsafe, as there is a window of time between generating the name and using it where another process can create an object by the same name.

Michael Hall
  • 2,834
  • 1
  • 22
  • 40