Skip to content

Instantly share code, notes, and snippets.

@rbairwell
Created July 22, 2022 10:12
Show Gist options
  • Save rbairwell/9b1bbf855b89516937301b23ca68b2a7 to your computer and use it in GitHub Desktop.
Save rbairwell/9b1bbf855b89516937301b23ca68b2a7 to your computer and use it in GitHub Desktop.
Bash snippet to log all output (stderr and stdout) to both the console and a log file without any other script changes needed.
#!/bin/bash
# Aby thing that is outputted to either stdout or stderr is then sent to _OUTPUT_LOG_FILE from that point on (along with going to console).
# Problem - when the script ends, "tee" seems to wait for input before continuing.
declare _OUTPUT_LOG_FILE="~/logoutput.txt"
# use base4.1+ timestamping %([%F %T])T
# shellcheck disable=SC2312
if ! exec > >(while read -r line; do printf '%([%F %T])T %s\n' -1 "${line}" | tee -ap --output-error=exit "${_OUTPUT_LOG_FILE}"; done) 2>&1; then
printf "Error %s encountered when trying to startup log file (no error available)\n" "$?"
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment