Building Bash Muscle (12)

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
  1. The first line executes mktemp command and sets the temporary file path into tmpfile variable.
  2. The second line prints the path of the temp file path.
  3. The third line adds the text ‘hello temp file’ into the temp file.
  4. 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
  1. 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.
  2. The second line creates foo.txt in the temporary directory.
  3. The third line adds ‘hello foo text’ to the text file.
  4. The fourth line prints the content of the foo.txt file under the temp directory.
  5. 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.

Author: admin

A software engineer in greater Seattle area

Leave a Reply

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