Overview
The mktemp
command creates a temporary file or directory safely, ensuring that the file name is unique to avoid any conflicts.
Syntax
- Basic usage for creating a temporary file:
mktemp
- For creating a temporary directory:
mktemp -d
Options
-d
: Create a directory instead of a file-t [template]
: Use a custom template for the filename
Use Case: Temporary File for Script Logging
Here’s a simple Bash script example that uses mktemp
to create a temporary log file. The script writes some output to this log file and then prints the contents.
#!/bin/bash
# Create a temporary file with a custom template
temp_log=$(mktemp -t mytemp_XXX)
# Perform some operations and redirect output to the temporary log file
echo "This is a test log entry" > "$temp_log"
# Display the log
echo "Temporary log created: $temp_log"
cat "$temp_log"
# Clean up
rm "$temp_log"