How to create a temporary file in Linux shell

Sometime you just need to quickly put down something in a temporary file. And as easy as it seems to just type in some file name like ‘test’, ‘test1’ and so on, this soon becomes wasteful and impractical.

In this article we’ll show you a bit more professional and programmable way to create temporary files in Linux usin ‘mktemp’.

So what can you do with ‘mktemp’. It is a basic Linux command used to generate temporary file and directory names.

When you need a quickly generated temporary file you simply run:

mktemp

It will come out with some file name like “/tmp/tmp.XYZXYZ”. By default ‘mktemp’ uses the ‘/tmp’ and that is a good practice to follow.

As we mentioned earlier you can also use it to generate temporary directories:

mktemp -d

And again it produces a directory named like “/tmp/tmp.XYZXYZ” in the /tmp folder.

So far you can create a temporary file or directory with a random name. But the best part of the ‘mktemp’ command is that you can use it in scripts.

To get the name of a new temporary file in a variable named ‘tmp_file’:

tmp_file=$(mktemp)

Now you can use the “$tmp_file” variable to access the new temp file created above:

echo “CloudBalkan” > $tmpfile

For more options you can also check the Linux man page – https://linux.die.net/man/1/mktemp

Keep your eye on the CloudBalkan Blog for more useful Linux tips and guides.