You can achieve this in Bash by using tee with process substitution and by ensuring that output is unbuffered. Additionally, you can prefix each line with the value of CURRENT_STEP and an ISO 8601 timestamp.
Here’s a complete solution:
✅ Requirements Recap
- Log all stdout/stderr from the script and its commands to a file.
- Show all output unbuffered on the terminal.
- Each log line must be prefixed with:
- The environment variable
CURRENT_STEP
- An ISO 8601 timestamp
✅ Solution
#!/bin/bash
LOGFILE="script.log"
# Function to add prefix (CURRENT_STEP + timestamp) to each line
prefix_lines() {
while IFS= read -r line; do
echo "[$CURRENT_STEP] [$(date +"%Y-%m-%dT%H:%M:%S%z")]: $line"
done
}
# Redirect stdout and stderr to a FIFO/temporary file descriptor
# and tee it to both console and log with prefixing
exec > >(stdbuf -oL tee >(prefix_lines >> "$LOGFILE")) \
2> >(stdbuf -oL tee >(prefix_lines >&2 >> "$LOGFILE"))
# Example commands - replace these with your actual logic
CURRENT_STEP="STEP_1"
echo "Starting step one"
some_command || echo "some_command failed, but continuing..."
CURRENT_STEP="STEP_2"
echo "Now doing step two"
another_command || echo "another_command failed"
# End of script
🔍 Explanation
stdbuf -oL: Forces line buffering so output appears immediately (unbuffered).
>(...): Process substitution — sends output to another command.
prefix_lines: A loop function that reads lines and prepends CURRENT_STEP and timestamp.
tee: Duplicates output to both console and log processing function.
>> "$LOGFILE": Appends to the log file.
>&2: Ensures stderr also goes to the console (with prefix).
🧪 Test It
To test without real commands:
echo "This is stdout"
echo "This is stderr" >&2
sleep 1
false
echo "Exit code was: $?"
⚠️ Notes
- Make sure
stdbuf is available (part of GNU coreutils). If not available on your system (e.g., macOS), use unbuffer or other tools.
- If you're running this in environments like CI pipelines or Docker, ensure logging behavior matches expectations.
- You can reset the environment variable
CURRENT_STEP before each logical block of commands.
Let me know if you want to rotate logs or colorize console output!