|
Temporary files are essential for shell scripts that
need to store intermediate data. The Basic temporary file with |
|
|
Output:
Created temp file: /tmp/tmp.stab000000 Hello, temp! |
|
|
mktemp creates unique files in $TMPDIR (or /tmp): |
|
|
Output:
TMPDIR: /tmp |
|
|
Custom prefix with template: |
|
|
Output:
Custom prefix: /tmp/myapp.stab00 |
|
|
At least 6 X’s are required for the random suffix. This ensures sufficient randomness in the filename. |
|
|
Output:
6 X's works: /tmp/data.stab00 More X's also works: /tmp/longer.stab000001 |
|
|
Create temporary directory: |
|
|
Output:
Created temp dir: /tmp/tmp.stab000000 file1.txt file2.txt |
|
|
Custom directory template: |
|
|
Output:
Custom temp dir: /tmp/myapp.stab00 |
|
|
Bash
You should always clean up temp files using |
|
|
Output:
Working with /tmp/tmp.stab000000 |
|
|
Multiple temp files with cleanup: |
|
|
Output:
Cleanup demo: Files: /tmp/tmp.stab000000, /tmp/tmp.stab000001 Dir: /tmp/tmp.stab000002 |
|
|
Named pipe (FIFO) for inter-process communication: |
|
|
Output:
Created FIFO: /tmp/tmp.stab000000 Received: message |
|
|
Bash
Using process substitution instead of temp files. This avoids creating explicit temp files: |
|
|
Output:
--- /dev/fd/63 +++ /dev/fd/62 @@ -1,3 +1,3 @@ apple banana -cherry +date |
|
|
POSIX alternative using named pipes: |
|
|
Output:
Diff of sorted inputs: --- /tmp/tmp.stab000000 +++ /tmp/tmp.stab000001 @@ -1,3 +1,3 @@ a -b c +d |
|
|
Secure temp file patterns. Don’t use predictable names
like |
|
|
Output:
-rw------- 1 root root 0 Jan 1 2025 /tmp/tmp.stab000000 |
|
|
Temp file in specific directory using a template |
|
|
Output:
Custom location: /tmp/myapp.stab00 |
|
|
Atomic file operations with temp files: |
|
|
Output:
Atomic content |
|
|
Collect output from multiple processes: |
|
|
Output:
Collected results: result1 result2 |
|
|
Here-document to temp file: |
|
|
Output:
From heredoc temp file: Line 1 Line 2 Line 3 |
|
|
In-memory temp file using /dev/shm (Linux): |
|
|
Output:
RAM-based temp: /dev/shm/myapp.stab00 |
|