0
0
Bash Scriptingscripting~5 mins

Temporary files (mktemp) in Bash Scripting

Choose your learning style9 modes available
Introduction
Temporary files let you store data safely for a short time while your script runs. They help avoid conflicts and keep your system clean.
When you need to save some data temporarily during a script run.
When multiple scripts run at the same time and need separate files.
When you want to avoid overwriting existing files by accident.
When you want the system to clean up files automatically after use.
Syntax
Bash Scripting
mktemp [OPTION]... [TEMPLATE]
If TEMPLATE is not given, mktemp creates a file with a random name in /tmp.
The TEMPLATE should end with at least 3 X's (e.g., tmp.XXXXXX) which mktemp replaces with random characters.
Examples
Creates a temporary file with a random name in /tmp and saves its name in the variable tempfile.
Bash Scripting
tempfile=$(mktemp)
echo $tempfile
Creates a temporary file with a name starting with 'tmp.' followed by random characters.
Bash Scripting
tempfile=$(mktemp tmp.XXXXXX)
echo $tempfile
Creates a temporary directory instead of a file.
Bash Scripting
tempdir=$(mktemp -d)
echo $tempdir
Sample Program
This script creates a temporary file, writes a message inside, shows the file path and contents, then deletes the file to keep things clean.
Bash Scripting
#!/bin/bash

# Create a temporary file
tempfile=$(mktemp)

# Write some text to it
echo "Hello, temporary file!" > "$tempfile"

# Show the file path and contents
echo "Temporary file created at: $tempfile"
echo "Contents:"
cat "$tempfile"

# Clean up by removing the temporary file
rm "$tempfile"
echo "Temporary file removed."
OutputSuccess
Important Notes
Always quote the variable holding the temporary file name to handle spaces or special characters safely.
Remember to delete temporary files after use to avoid cluttering the system.
Using mktemp -d creates a temporary directory instead of a file.
Summary
mktemp creates safe temporary files or directories with unique names.
Use temporary files to avoid conflicts and keep your scripts clean.
Always remove temporary files when done to keep your system tidy.