|
|
|
Temporary files are essential for shell scripts that
need to store intermediate data. The |
|
|
Basic temporary file with mktemp: |
|
|
mktemp creates unique files in $TMPDIR (or /tmp): |
|
|
Custom prefix with template: |
|
|
At least 6 X’s are required for the random suffix. |
|
|
Create temporary directory: |
|
|
Custom directory template: |
|
|
Always clean up temp files - use trap: |
|
|
Multiple temp files with cleanup: |
|
|
Named pipe (FIFO) for inter-process communication: |
|
|
Bash
Using process substitution instead of temp files. This avoids creating explicit temp files: |
|
|
POSIX alternative using named pipes: |
|
|
Secure temp file patterns: |
|
|
Don’t do this (predictable, race condition): bad_tmpfile=“/tmp/myapp.$$” # PID is predictable |
|
|
Do this instead: |
|
|
Set restrictive permissions: |
|
|
Temp file in specific directory: |
|
|
Check temp space before creating large files: |
|
|
Atomic file operations with temp files: |
|
|
Collect output from multiple processes: |
|
|
Here-document to temp file: |
|
|
In-memory temp file using /dev/shm (Linux): |
|
|
Fallback if mktemp is unavailable: |
|