Skip to content

Instantly share code, notes, and snippets.

@kaznak
Last active April 6, 2022 01:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaznak/56d450339dc9c154b96c04d9161676f6 to your computer and use it in GitHub Desktop.
Save kaznak/56d450339dc9c154b96c04d9161676f6 to your computer and use it in GitHub Desktop.
My shellscript template
#!/bin/bash
set -Cu
set -Ee
set -o pipefail
shopt -s nullglob
stime=$(date +%Y%m%d%H%M%S%Z)
based=$(readlink -f $(dirname $0)/..)
pname=$(basename $0)
exec 3>&2
# logd=$based/log
# exec 3>&2 2>$logd/$pname.$stime.$$.log
# set -vx
MSG() {
echo "$pname pid:$$ stime:$stime etime:$(date +%Y%m%d%H%M%S%Z) $@" >&3
}
tmpd=$(mktemp -d -t "$pname.$stime.$$.XXXXXXXX")/
if [ 0 -ne "$?" ] ; then
MSG "line:$LINENO FATAL can not make temporally directory."
exit 1
fi
trap 'BEFORE_EXIT' EXIT
BEFORE_EXIT() {
rm -rf $tmpd
}
trap 'ERROR_HANDLER' ERR
export EMSG="line:$LINENO ERROR"
ERROR_HANDLER() {
MSG "line:$LINENO ERROR status ${PIPESTATUS[@]}"
[ "$EMSG" ] && MSG $EMSG
touch $tmpd/ERROR # for child process error detection
MSG "line:$LINENO EXIT with error."
exit 1 # root process trigger BEFORE_EXIT function
}
PROGRESS() {
lineno="$1"
shift
PMSG="$*"
MSG "line:$lineno INFO $PMSG"
EMSG="line:$lineno ERROR while $PMSG"
}
################################################################
PROGRESS "$LINENO" "testing script"
MSG "line:$LINENO INFO This is a message."
EMSG="line:$LINENO FATAL unreachable."
true
EMSG="line:$LINENO INFO while forking child process."
(
EMSG="line:$LINENO INFO child process 1 error"
true | false | true
) &
(
set +o pipefail
EMSG="line:$LINENO INFO child process 2 error"
true | false | true
) &
EMSG="line:$LINENO INFO while waiting child process."
wait
[ ! -e $tmpd/ERROR ]
################################################################
PROGRESS "$LINENO" "exiting"
shopt -u nullglob
MSG "line:$LINENO EXIT without error."
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment