I will introduce a command mktemp. According to the man page “mktemp – create a temporary file or directory”.
Let’s create a temp file and write some text in it.
$ tmpfile=$(mktemp) $ echo $tmpfile $ echo 'hello temp file' >> $tmpfile $ cat $tmpfile $ rm -rf $tmpfile
- The first line executes mktemp command and sets the temporary file path into tmpfile variable.
- The second line prints the path of the temp file path.
- The third line adds the text ‘hello temp file’ into the temp file.
- The fourth line prints out the content of the temp file. The last one removes the file.
Now let’s create a temp directory.
$ tmpdir=$(mktemp -d) $ touch $tmpdir/foo.txt $ echo 'hello foo text' >> $tmpdir/foo.txt $ cat $tmpdir/foo.txt $ rm -rf $tmpdir
- The first line creates a temp directory and sets the temp directory path to tmpdir variable. The -d option tells mktemp to create a temporary directory.
- The second line creates foo.txt in the temporary directory.
- The third line adds ‘hello foo text’ to the text file.
- The fourth line prints the content of the foo.txt file under the temp directory.
- The fifth line removes the temp directory along with the foo.txt file underneath it.
To recap, mktemp can be used to create a temporary file or directory safely to work with them for possible atomic processing.