initial commit
This commit is contained in:
parent
f3f64ea1f1
commit
75143b96f3
73
log.output.bash
Normal file
73
log.output.bash
Normal file
@ -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
|
Loading…
Reference in New Issue
Block a user