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

Use temp file with cleanup


 # Function to create a temporary file
 create_temp_file() {
 local temp_file
 temp_file=$(mktemp /tmp/my_script.XXXXXX)
 echo "$temp_file"
 }

 # Function to handle cleanup
 cleanup() {
 echo "Cleaning up temporary files..."
 rm -f "$temp_file"
 }

 # Setting up the trap for SIGINT and EXIT
 trap cleanup SIGINT EXIT

 # Create a temporary file
 temp_file=$(create_temp_file)
 echo "Temporary file created at $temp_file"

 # Simulate a task with the temporary file
 echo "Processing with $temp_file..."
 sleep 10

 # Normal cleanup executed if no interruption occurs
 cleanup