diff --git a/log.output.bash b/log.output.bash new file mode 100644 index 0000000..b02ac95 --- /dev/null +++ b/log.output.bash @@ -0,0 +1,73 @@ +#!/bin/bash +logfile=/tmp/test.log + +# Exit-handler to stop all output redirection. +on_exit() { + local rv="$?" + + # Print message to console and logfile. + echo "INFO: Finished at $(date -R), PID $$, exit code $rv" >&2 + + # Restore previous standard output and error from FDs 3 and 4; + # this will cause the "tee" sub-processes to terminate (EOF); + exec 1>&3 2>&4 + + # Reap the sub-processes and evaluate their exit codes. + + wait "$stdout_pid" + stdout_rv=$? + wait "$stderr_pid" + stderr_rv=$? + + # Print final report to console only. + + if [[ $stdout_rv -ne 0 ]] || [[ $stderr_rv -ne 0 ]] + then + echo "ERROR: Output redirection to $logfile may be incomplete." >&2 + fi + + echo "Done (exit code: $rv, see $logfile for details)." >&2 +} + +# Initially, no output is logged. +# Perform some initial greeting / interactions here ... + +echo "Note: The following procedure will be logged to $logfile." +[[ -t 0 ]] && read -rp 'Press ENTER to continue' + +# Copy original output FD to FD 3 and original error FD to FD 4. +exec 3>&1 4>&2 + +# Redirect standard output and error to sub-processes. +# Store sub-process PIDs for later reaping. + +exec 1> >(tee -ai "$logfile") +stdout_pid=$! + +exec 2> >(tee -ai "$logfile" >&2) +stderr_pid=$! + +# Register exit-handler. +trap on_exit EXIT + +# From here on, all output will be logged to $logfile. + +# Print a startup report. +echo "INFO: Starting at $(date -R), PID $$ ..." >&2 + +######################## +# EXAMPLE WORKLOAD BEGIN + +# Find and report temporary files older than 15 days. +# Note: May encounter "permission denied" errors if run as non-root user. + +if ! find /tmp -mtime +15 -exec ls -ld "{}" \; +then + echo "ERROR: \"find\" command failed." >&2 + exit 2 +fi + +# EXAMPLE WORKLOAD END +###################### + +exit 0 \ No newline at end of file