bash mktemp - ghdrako/doc_snipets GitHub Wiki

create unique temporary files

#!/bin/bash

for f in 1 2 3
do
  file=$(mktemp)
  echo "Writing file $file"
  echo "My Contents" >> $file
done

Using a Name Template

Using the -t option with mktemp allows us to define a prefix for the temporary files.

#!/bin/bash

for f in 1 2 3
do
  file=$(mktemp -t file_${f})
  echo "Writing file $file"
  echo "My Contents" >> $file
done

Note that in this case, the ${f} is not required to use -t. It’s to get our loop variable into our file name template.

Using mktemp for a Temporary Directory

create a temporary directory (using -d)

#!/bin/bash

dir=$(mktemp -d)
for f in 1 2 3
do
  file=file_$f.txt
  echo "Writing file $file to dir $dir"
  echo "My Contents" >> "$dir/$file"
done
...
rm -r $dir  # remove temporary dir