Linux - How create a temporary file in shell script?

By xngo on March 29, 2020

In Linux, you can create a temporary file using the mktemp command.

Create temporary file

To create a temporary file using mktemp command, you need to supply the path and the X template. The number of Xs template represent the length of the random name. But, you need at least 3 Xs.

mktemp /tmp/my-script.XXXXXX
#   /tmp/my-script.ycOanK

Create temporary directory

Using the same principle as creating a temporary file, you add the -d option to the mktemp command.

mktemp -d /tmp/my-temp-dir-XXXXXX
#   /tmp/my-temp-dir-KdQmhE

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.