-
Notifications
You must be signed in to change notification settings - Fork 0
/
lib
executable file
·77 lines (64 loc) · 1.54 KB
/
lib
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/usr/bin/env bash
#{{{ Bash settings
# debug script
# set -x
# abort on nonzero exitstatus
set -o errexit
# abort on unbound variable
set -o nounset
# don't hide errors within pipes
set -o pipefail
# error trace on
set -o errtrace
#}}}
#{{{ Variables
IFS=$'\t\n' # Split on newlines and tabs (but not on spaces)
_script_name=$(basename "${0}")
_script_dir=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )
readonly _script_name _script_dir
TMPDIR=$(mktemp -d)
pidfile="$TMPDIR/pidfile"
out="$TMPDIR/out"
err="$TMPDIR/err"
mkfifo "$out" "$err"
<"$out" journ -p user.notice -t "$_script_name" &
<"$err" logger -p user.error -t "$_script_name" &
# requires `set -o errtrace`
err_report() {
local error_code=${?}
error "Error in ${_script_name} in function ${1} on line ${2}"
exit ${error_code}
}
#Cleanup mechanism
function finish {
result=$?
# Your cleanup code here
pid=$(cat "$pidfile") ||
[[ -f $pid ]] && kill -s SIGTERM "$pid" ||
[[ ! "$(rm -rf "$TMPDIR")" && $result -eq 0 ]] && {
echo "Exit success."
exit 0
} || exit ${result}
}
#Will trigger finish on EXIT or ERR or when receiving SIGQUIT or SIGTERM
trap "finish" EXIT ERR SIGQUIT SIGTERM
#trap ERR to get the error report
trap 'err_report "${FUNCNAME:-.}" ${LINENO}' ERR
export ERR_BAD=100
export ERR_WORSE=101
export ERR_CRITICAL=102
function try()
{
[[ $- = *e* ]]; SAVED_OPT_E=$?
set +e
}
function throw()
{
exit "$1"
}
function catch()
{
export exception_code=$?
(( "$SAVED_OPT_E" )) && set +e
return $exception_code
}