Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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 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() {
[ "$EMSG" ] && MSG $EMSG
touch $tmpd/ERROR # for child process error detection
exit 1 # root process trigger BEFORE_EXIT function
}
################################################################
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 ]
################################################################
EMSG="line:$LINENO FATAL while exiting"
shopt -u nullglob
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.