How to make a unique temporary file in Bash on Linux?

It is common to make a unique temporary file. How to make a unique temporary file in Bash on Linux safely and quickly?

You can use the mktemp program.

In the simplest way,

tmpfile=$(mktemp)

The file will be like /tmp/tmp.j0wD39Mr3b if you do not prefer any meaningful names.

You can set the file to your preferred string like myapp.<6 char random string> by

tmpfile=$(mktemp -t myapp.XXXXXX)

Your temporary file will be like /tmp/myapp.V9XnA6.

You may also choose the directory where the temporary file is in by setting the -p option.

Check more about mktemp in mktemp man page.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

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