Skip to content

Instantly share code, notes, and snippets.

@witalisoft
Last active April 22, 2017 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save witalisoft/80da279e061c96d1e09dd3bd4e6fb907 to your computer and use it in GitHub Desktop.
Save witalisoft/80da279e061c96d1e09dd3bd4e6fb907 to your computer and use it in GitHub Desktop.
#!/bin/bash
#
# <script_name> <desc>
# Author: <author>
#
set -o errtrace
readonly LOG_DIR="/tmp/log"
readonly LOG_FILE="output.log"
assert() {
[ -d $LOG_DIR ] \
|| mkdir -p $LOG_DIR
}
configure_logger() {
local timeformat="+%Y%m%d_%H%M%S"
local log_endpoint="${LOG_DIR}/${LOG_FILE}"
coproc LOGGER {
while read -r line; do
echo "[$(date $timeformat)] $line" >> $log_endpoint
done
}
exec 3>&1
exec 4>&2
exec 1>&${LOGGER[1]}
exec 2>&1
}
restore_exec_redirect() {
exec 1>&3
exec 2>&4
}
logging() {
if [ $? -ne 0 ]; then
echo "failed on: $BASH_COMMAND"
restore_exec_redirect
echo "failed on: $BASH_COMMAND"
exit 1
else
echo "+ $BASH_COMMAND"
fi
}
helloworld() {
echo "hello world!"
}
sampletask() {
echo "first step"
echo "second step"
}
main() {
assert
configure_logger
trap "logging" DEBUG ERR
helloworld
sampletask
echo "end"
}
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment