How to create a temporary file on Linux using Bash? 👋
Depending on the OS the command varies. mktemp and tempfile are the commands used in the Bash script to create temporary file - it is easy, readily available and simple to use.
Temporary file creation in Bash
It is must to have feature in all the programming languages - an ability to create temporary files or intermediary file. These files are called temporary files but that does not mean that it will be deleted from the disk after a time period. In Linux, based on the distribution we have two commands to create temporary files -
In this article we explore ways to (1) how to create temporary file, (2) how to store the name of the temporary file created in a variable, (3) how to customize the name of temporary file by adding prefix and suffix, (4) tempfile as touch or vim, (5) how to create a directory with
How to create a temporary file?
$ tempfile /tmp/R4FkiHL
Simple, right? If you din’t specify a directory name the
tempfile command will create a temporary file in the
Now let’s try
$ mktemp /tmp/tmp.HtOPhjkH
How to create a temporary file inside a directory of your wish?
To create a file inside a directory specify the directory name as shown below:
mktemp use the
$ mktemp -p ~/dirname /home/fluentprogrammer/dirname/kldyuonYUkh
tempfile use the
$ tempfile --directory ~/dirname /home/fluentprogrammer/dirname/kldyuonYUkh $ tempfile -d ~/dirname /home/fluentprogrammer/dirname/kldyuonYUkh
Make sure the directory is already present or else it will show an error as shown below
$ tempfile -p ~/dirname mkstemps: No such file or directory
How to customize the temporary file names?
–suffix are used to customize the name of the file as shown below
$ mktemp -p ~/dirname/ --suffix .txt /home/fluentprogrammer/dirname/HKhjegKHGGK.txt $ tempfile --directory ~/dirname/ --prefix howto_ --suffix .txt /home/fluentprogrammer/dirname/howto_hksgJKGGK.txt
But if we mention the name of the file explicitly then
–suffix does not work.
$ tempfile --name hello_i_am_explicitly_mentioned --prefix howto_ --suffix .txt /tmp/hello_i_am_explicitly_mentioned
How to find the name of the temporary file?
tempfile are good to create temporary files inside the
/tmp/ as well as inside the directory of your wish but it is not returning the name of the file. If we want to use this comment in the bash script then it should be having the capability to return the file name. And yeah, It can return back the file name after creation. Check the below code,
$ TMPFILE=$(mktemp -p ~/dirname) $ echo $TMPFILE /home/fluentprogrammer/dirname/HKhjegKHGGK $ TMPFILE=$(tempfile -d ~/dirname) $ echo $TMPFILE /home/fluentprogrammer/dirname/jkhjttYKHHQ
mktemp to create temporary files, customize it, store the file name in a variable so we could use it in subsequent commands in the bash script, etc.