-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathbashinator.lib.0.sh
1555 lines (1348 loc) · 40.9 KB
/
bashinator.lib.0.sh
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## vim:ts=4:sw=4:tw=200:nu:ai:nowrap:
##
## bashinator shell script framework library
##
## Created by Wolfram Schlich <[email protected]>
## Licensed under the GNU GPLv3
## Web: http://www.bashinator.org/
## Code: https://github.com/wschlich/bashinator/
##
##
## REQUIRED PROGRAMS
## =================
## - rm
## - touch
## - mktemp
## - cat
## - logger
## - sed
## - date
## - sendmail (default /usr/sbin/sendmail, can be overridden with __SendmailBin)
##
##
## GLOBAL VARIABLES
## ======================================
## D: defined by bashinator
## u: used by bashinator if defined
## --------------------------------------
##
## D: __BashinatorRequiredBashVersion
##
## u: __DieExitCode
## u: __ScriptExitCode
## u: __ScriptDieExitCode
##
## u: __ScriptFile
## u: __ScriptPath
## u: __ScriptName
## u: __ScriptHost
## u: __ScriptLock
## D: __ScriptLockFile
## u: __ScriptLockDir
## u: __ScriptSubCommandLog
## D: __ScriptSubCommandLogFile + _L
## u: __ScriptSubCommandLogDir
## u: __ScriptUseSafePathEnv
## u: __ScriptUmask
##
## D: __MsgArray
## u: __MsgQuiet
## u: __MsgTimestampFormat
##
## u: __PrintDebug
## u: __PrintInfo
## u: __PrintNotice
## u: __PrintWarning
## u: __PrintErr
## u: __PrintCrit
## u: __PrintAlert
## u: __PrintEmerg
## u: __PrintPrefixTimestamp
## u: __PrintPrefixSeverity
## u: __PrintPrefixSource
## u: __PrintPrefixSeverity7
## u: __PrintPrefixSeverity6
## u: __PrintPrefixSeverity5
## u: __PrintPrefixSeverity4
## u: __PrintPrefixSeverity3
## u: __PrintPrefixSeverity2
## u: __PrintPrefixSeverity1
## u: __PrintPrefixSeverity0
## u: __PrintColorSeverity7
## u: __PrintColorSeverity6
## u: __PrintColorSeverity5
## u: __PrintColorSeverity4
## u: __PrintColorSeverity3
## u: __PrintColorSeverity2
## u: __PrintColorSeverity1
## u: __PrintColorSeverity0
##
## u: __LogDebug
## u: __LogInfo
## u: __LogNotice
## u: __LogWarning
## u: __LogErr
## u: __LogCrit
## u: __LogAlert
## u: __LogEmerg
## u: __LogPrefixTimestamp
## u: __LogPrefixSeverity
## u: __LogPrefixSource
## u: __LogPrefixSeverity7
## u: __LogPrefixSeverity6
## u: __LogPrefixSeverity5
## u: __LogPrefixSeverity4
## u: __LogPrefixSeverity3
## u: __LogPrefixSeverity2
## u: __LogPrefixSeverity1
## u: __LogPrefixSeverity0
## u: __LogColorSeverity7
## u: __LogColorSeverity6
## u: __LogColorSeverity5
## u: __LogColorSeverity4
## u: __LogColorSeverity3
## u: __LogColorSeverity2
## u: __LogColorSeverity1
## u: __LogColorSeverity0
## u: __LogTarget
## D: __LogFileHasBeenWrittenTo
##
## u: __MailDebug
## u: __MailInfo
## u: __MailNotice
## u: __MailWarning
## u: __MailErr
## u: __MailCrit
## u: __MailAlert
## u: __MailEmerg
## u: __MailPrefixTimestamp
## u: __MailPrefixSeverity
## u: __MailPrefixSource
## u: __MailPrefixSeverity7
## u: __MailPrefixSeverity6
## u: __MailPrefixSeverity5
## u: __MailPrefixSeverity4
## u: __MailPrefixSeverity3
## u: __MailPrefixSeverity2
## u: __MailPrefixSeverity1
## u: __MailPrefixSeverity0
## u: __MailColorSeverity7
## u: __MailColorSeverity6
## u: __MailColorSeverity5
## u: __MailColorSeverity4
## u: __MailColorSeverity3
## u: __MailColorSeverity2
## u: __MailColorSeverity1
## u: __MailColorSeverity0
## u: __MailFrom
## u: __MailEnvelopeFrom
## u: __MailRecipient
## u: __MailSubject
##
## u: __SendmailBin
## u: __SendmailArgs
##
## D: __TrapSignals
##
## u: BASH_VERSINFO
## u: EUID
## D: PATH
## u: TERM
## u: USER
##
## basic shell settings (must not be placed in a conditional context)
shopt -s extglob # enable extended globbing (required for pattern matching)
shopt -s extdebug # enable extended debugging (required for function stack trace)
hash -r # reset hashed command paths
set +m # disable monitor mode (job control)
## define the required minimum bash version for this
## bashinator release to function properly
export __BashinatorRequiredBashVersion=3.2.0
##
## bashinator control functions
##
function __boot() {
## ----- head -----
##
## DESCRIPTION:
## initializes bashinator
##
## ARGUMENTS:
## /
##
## GLOBAL VARIABLES USED:
## __BashinatorRequiredBashVersion (default: 0.0.0)
## __ScriptUseSafePathEnv (default: 1)
## __ScriptUmask (default: 077)
## BASH_VERSINFO
## EUID
## PATH
##
## check for required bash version
IFS='.'
set -- ${__BashinatorRequiredBashVersion:-0.0.0}
unset IFS
local -i requiredBashMajorVersion=${1}
local -i requiredBashMinorVersion=${2}
local -i requiredBashPatchLevel=${3}
set --
## create sets of version component numbers to compare
## one by one, starting with the major version
local -a versionsToCompare=(
${BASH_VERSINFO[0]}:${requiredBashMajorVersion}
${BASH_VERSINFO[1]}:${requiredBashMinorVersion}
${BASH_VERSINFO[2]}:${requiredBashPatchLevel}
)
## loop through sets of version component numbers
local versionSet
for versionSet in "${versionsToCompare[@]}"; do
IFS=':'
set -- ${versionSet}
unset IFS
currentVersion=${1}
requiredVersion=${2}
set --
## check whether current version > required version
if [[ ${currentVersion} -gt ${requiredVersion} ]]; then
## version requirements are completely satisfied,
## so we finish overall comparison
break
## check whether current version < required version
elif [[ ${currentVersion} -lt ${requiredVersion} ]]; then
## version requirements are not satisfied at all,
## so we error out
echo "!!! FATAL: bashinator requires at least bash version ${__BashinatorRequiredBashVersion}" 1>&2
exit 2 # error
## check whether current version == required version
## (this is implicitly true, it's just here for clarity)
elif [[ ${currentVersion} -eq ${requiredVersion} ]]; then
## version requirements are satisfied up to the
## current version number component, so we
## compare the next versionSet (if any)
continue
fi
done
## use a safe PATH environment variable by default
if [[ ${__ScriptUseSafePathEnv:-1} -eq 1 ]]; then
## default PATH when running as a non-root user
export PATH="/bin:/usr/bin"
## extend PATH if we are running as root
if [[ ${EUID} -eq 0 ]]; then
export PATH="/sbin:/usr/sbin:${PATH}"
fi
fi
## use a secure umask by default
umask ${__ScriptUmask:-077}
return 0 # success
} # __boot()
function __dispatch() {
## ----- head -----
##
## DESCRIPTION:
## dispatches the application.
## calls the __init() and __main()
## functions that have to be defined by the user.
##
## ARGUMENTS:
## *: all arguments of the originally executed script
##
## GLOBAL VARIABLES USED:
## __ScriptExitCode: can be set to a custom exit code from within
## the user functions
##
## check for user defined __init() function
if ! declare -F __init &>/dev/null; then
__die ${__DieExitCode:-2} "function __init() does not exist, unable to dispatch application"
fi
## check for user defined __main() function
if ! declare -F __main &>/dev/null; then
__die ${__DieExitCode:-2} "function __main() does not exist, unable to dispatch application"
fi
## ----- main -----
## init application function
__init "${@}" || __die ${?} "__init() failure"
## main application pre-processing (create lockfile and subcommand logfile)
__prepare || __die ${__DieExitCode:-2} "__prepare() failure"
## main application function
__main || __die ${?} "__main() failure"
## main application post-processing (remove lockfile and subcommand logfile)
__cleanup || __die ${__DieExitCode:-2} "__cleanup() failure"
## backwards compatibility for user specified exit code
if [[ -n "${Exit}" ]]; then
exit ${Exit}
fi
## exit script with optional user specified exit code
exit ${__ScriptExitCode:-0}
} # __dispatch()
function __prepare() {
## ----- head -----
##
## DESCRIPTION:
## run application main pre-processing tasks
##
## ARGUMENTS:
## /
##
## GLOBAL VARIABLES USED:
## __ScriptSubCommandLog (default: 0)
## __ScriptSubCommandLogFile
## __ScriptLock (default: 0)
## __ScriptLockFile
##
## ----- main -----
## handle script subcommand logfile
if [[ ${__ScriptSubCommandLog:-0} == 1 ]]; then
## create temporary logfile
__ScriptSubCommandLogFile=$(mktemp -q -t -p "${__ScriptSubCommandLogDir:-/var/log}" ${__ScriptName:-${0##*/}}.log.XXXXXX)
if [[ -z "${__ScriptSubCommandLogFile}" ]]; then
__msg alert "failed to create temporary script subcommand logfile in script logdir '${__ScriptSubCommandLogDir:-/var/log}'"
return 2 # error
else
__msg debug "successfully created temporary script subcommand logfile '${__ScriptSubCommandLogFile}'"
fi
else
## if sub command logging is disabled, set logfile to
## /dev/null to make redirections work nevertheless.
__ScriptSubCommandLogFile="/dev/null"
fi
export __ScriptSubCommandLogFile _L=${__ScriptSubCommandLogFile} # use _L as a shorthand
__msg debug "script subcommand logfile: '${__ScriptSubCommandLogFile}'"
## handle script lockfile
if [[ ${__ScriptLock:-0} == 1 ]]; then
__ScriptLockFile="${__ScriptLockDir:-/var/lock}/${__ScriptName:-${0##*/}}.lock"
## check/create lockfile
if [[ -e "${__ScriptLockFile}" ]]; then
__msg alert "script lockfile '${__ScriptLockFile}' already exists"
return 2 # error
elif ! touch "${__ScriptLockFile}" >>"${_L}" 2>&1; then
__msg alert "failed to create script lockfile '${__ScriptLockFile}'"
return 2 # error
else
__msg debug "successfully created script lockfile '${__ScriptLockFile}'"
fi
fi
return 0 # success
} # __prepare()
function __cleanup() {
## ----- head -----
##
## DESCRIPTION:
## run application main post-processing tasks
##
## ARGUMENTS:
## /
##
## GLOBAL VARIABLES USED:
## __ScriptSubCommandLog (default: 0)
## __ScriptSubCommandLogFile
## __ScriptLock (default: 0)
## __ScriptLockFile
##
## ----- main -----
## remove script subcommand logfile
if [[ ${__ScriptSubCommandLog:-0} == 1 && "${__ScriptSubCommandLogFile}" != /dev/null ]]; then
__msg debug "removing script subcommand logfile '${__ScriptSubCommandLogFile}'"
if ! rm -f "${__ScriptSubCommandLogFile}" &>/dev/null; then
__msg alert "failed to remove script subcommand logfile '${__ScriptSubCommandLogFile}'"
return 2 # error
else
__msg debug "successfully removed script subcommand logfile '${__ScriptSubCommandLogFile}'"
fi
fi
## remove script lockfile
if [[ ${__ScriptLock:-0} == 1 ]]; then
__msg debug "removing script lockfile '${__ScriptLockFile}'"
if ! rm -f "${__ScriptLockFile}" &>/dev/null; then
__msg alert "failed to remove script lockfile '${__ScriptLockFile}'"
return 2 # error
else
__msg debug "successfully removed script lockfile '${__ScriptLockFile}'"
fi
fi
return 0 # success
} # __cleanup()
function __die() {
## ----- head -----
##
## DESCRIPTION:
## terminate the currently executing script
##
## ARGUMENTS:
## 1: exit code (opt, default: 1)
## 2: message (opt): the message explaining the termination
##
## GLOBAL VARIABLES USED:
## /
##
local -i exitCode="${1}"; shift
local message="${1}"; shift
## ----- main -----
## check for exit code
if [[ -z "${exitCode}" ]]; then
let exitCode=1
fi
## check for error message
if [[ -z "${message}" ]]; then
message="<called ${FUNCNAME[0]}() without message>"
fi
## display main error message
__msg alert "${message}"
## generate stack trace
if [[ "${__ScriptGenerateStackTrace:-1}" -eq 1 ]]; then
## number of functions involved
local -i numberOfFunctions=$((${#FUNCNAME[@]} - 1))
## skip this number of functions from the bottom of the call stack
## 1 == only skip this function itself
local -i skipNumberOfFunctions=1
## display function call stack (if any functions are involved)
if [[ "${numberOfFunctions}" > "${skipNumberOfFunctions}" ]]; then
__msg alert "function call stack (most recent last):"
## n: current function array pointer (initially the last element of the FUNCNAME array)
## p: current parameter pointer (initially the last element of the BASH_ARGV array)
## bashFileName: source file of previous function that called the current function
## bashLineNumber: line in file that called the function
## functionName: name of called function
local -i n=0 p=0 bashLineNumber=0
local bashFileName= functionName=
for ((n = ${#FUNCNAME[@]} - 1, p = ${#BASH_ARGV[@]} - 1; n >= ${skipNumberOfFunctions}; n--)) ; do
bashFileName="${BASH_SOURCE[n + 1]##*/}"
bashLineNumber="${BASH_LINENO[n]}"
functionName="${FUNCNAME[n]}"
## get function arguments (bash3 only)
if [[ ${#BASH_ARGC[n]} -gt 0 ]]; then
## argList: list of quoted arguments of current function
## arg: next argument
local argList= arg=
## a: current function argument count pointer
local -i a=0
for ((a = 0; a < ${BASH_ARGC[n]}; ++a)); do
arg="${BASH_ARGV[p - a]}"
argList="${argList:+${argList},}'${arg}'"
done
## decrement parameter pointer by the count of parameters of the current function
(( p -= ${BASH_ARGC[n]} ))
fi
## skip main function
if [[ ${FUNCNAME[n]} == "main" ]]; then
continue
fi
## print function information
__msg alert "--> ${functionName}(${argList:+${argList}}) called in '${bashFileName}' on line ${bashLineNumber}"
done
fi
fi
## mention path to script subcommand log if enabled and not empty
if [[ ${__ScriptSubCommandLog:-0} -eq 1 \
&& ${__ScriptSubCommandLogFile} != /dev/null \
&& -s ${__ScriptSubCommandLogFile} ]]; then
__msg alert "please check script subcommand log '${__ScriptSubCommandLogFile}' for details"
fi
__msg alert "terminating script"
exit ${exitCode}
} # __die()
##
## bashinator message functions
##
function __msgPrint() {
## ----- head -----
##
## DESCRIPTION:
## prints a message.
## this function is NOT intended to be called by the user!
##
## ARGUMENTS:
## 1: timestamp (req): timestamp of the message
## 2: severity (req): severity of the message
## 3: source (req): source of the message (file, line, function)
## 4: message (req): the message to print
##
## GLOBAL VARIABLES USED:
## __PrintDebug (default: 0)
## __PrintInfo (default: 1)
## __PrintNotice (default: 1)
## __PrintWarning (default: 1)
## __PrintErr (default: 1)
## __PrintCrit (default: 1)
## __PrintAlert (default: 1)
## __PrintEmerg (default: 1)
## __PrintPrefixScriptNamePid (default: 1)
## __PrintPrefixTimestamp (default: 1)
## __PrintPrefixSeverity (default: 1)
## __PrintPrefixSource (default: 1)
## __PrintPrefixSeverity7 (default: >>> [____DEBUG])
## __PrintPrefixSeverity6 (default: >>> [_____INFO])
## __PrintPrefixSeverity5 (default: >>> [___NOTICE])
## __PrintPrefixSeverity4 (default: !!! [__WARNING])
## __PrintPrefixSeverity3 (default: !!! [____ERROR])
## __PrintPrefixSeverity2 (default: !!! [_CRITICAL])
## __PrintPrefixSeverity1 (default: !!! [____ALERT])
## __PrintPrefixSeverity0 (default: !!! [EMERGENCY])
## __PrintColorSeverity7 (default: 1;34)
## __PrintColorSeverity6 (default: 1;36)
## __PrintColorSeverity5 (default: 1;32)
## __PrintColorSeverity4 (default: 1;33)
## __PrintColorSeverity3 (default: 1;31)
## __PrintColorSeverity2 (default: 1;37;41)
## __PrintColorSeverity1 (default: 1;33;41)
## __PrintColorSeverity0 (default: 1;37;45)
## TERM (used to determine if we are running inside a terminal supporting colors)
##
local timestamp="${1}"; shift
local severity="${1}"; shift
local source="${1}"; shift
local message="${1}"; shift
## ----- main -----
## check whether message is to be printed at all
case ${severity} in
debug|7) if [[ ${__PrintDebug:-0} -ne 1 ]]; then return 0; fi ;;
info|6) if [[ ${__PrintInfo:-1} -ne 1 ]]; then return 0; fi ;;
notice|5) if [[ ${__PrintNotice:-1} -ne 1 ]]; then return 0; fi ;;
warning|4) if [[ ${__PrintWarning:-1} -ne 1 ]]; then return 0; fi ;;
err|3) if [[ ${__PrintErr:-1} -ne 1 ]]; then return 0; fi ;;
crit|2) if [[ ${__PrintCrit:-1} -ne 1 ]]; then return 0; fi ;;
alert|1) if [[ ${__PrintAlert:-1} -ne 1 ]]; then return 0; fi ;;
emerg|0) if [[ ${__PrintEmerg:-1} -ne 1 ]]; then return 0; fi ;;
esac
## determine whether we can show colors
local -i colorTerm=0
case "${TERM}" in
rxvt*|screen*|xterm*) let colorTerm=1 ;;
*) let colorTerm=0 ;;
esac
## show colors on stdout/stderr only if
## on a terminal (not redirected)
local -i colorStdout=0 colorStderr=0
if [[ -t 1 && ${colorTerm} -eq 1 ]]; then
let colorStdout=1
fi
if [[ -t 2 && ${colorTerm} -eq 1 ]]; then
let colorStderr=1
fi
## mapping severity -> stderr/severityPrefix/color
local severityPrefix= color=
local -i stderr=0
case ${severity} in
debug|7)
severityPrefix="${__PrintPrefixSeverity7:->>> [____DEBUG]}"
color="1;34" # blue on default
let stderr=0
;;
info|6)
severityPrefix="${__PrintPrefixSeverity6:->>> [_____INFO]}"
color="1;36" # cyan on default
let stderr=0
;;
notice|5)
severityPrefix="${__PrintPrefixSeverity5:->>> [___NOTICE]}"
color="1;32" # green on default
let stderr=0
;;
warning|4)
severityPrefix="${__PrintPrefixSeverity4:-!!! [__WARNING]}"
color="1;33" # yellow on default
let stderr=1
;;
err|3)
severityPrefix="${__PrintPrefixSeverity3:-!!! [____ERROR]}"
color="1;31" # red on default
let stderr=1
;;
crit|2)
severityPrefix="${__PrintPrefixSeverity2:-!!! [_CRITICAL]}"
color="1;37;41" # white on red
let stderr=1
;;
alert|1)
severityPrefix="${__PrintPrefixSeverity1:-!!! [____ALERT]}"
color="1;33;41" # yellow on red
let stderr=1
;;
emerg|0)
severityPrefix="${__PrintPrefixSeverity0:-!!! [EMERGENCY]}"
color="1;37;45" # white on magenta
let stderr=1
;;
esac
##
## final message structure in order (components can be disabled):
## timestamp severityPrefix source message
##
local messagePrefix
## 1. prefix message with source?
if [[ -n ${source} ]]; then
case ${__PrintPrefixSource:-1} in
1) messagePrefix="${source}: ${messagePrefix}" ;;
*) ;;
esac
fi
## 2. prefix message with severity?
case ${__PrintPrefixSeverity:-1} in
1) messagePrefix="${severityPrefix} ${messagePrefix}" ;;
*) ;;
esac
## 3. prefix message with timestamp?
case ${__PrintPrefixTimestamp:-1} in
1) messagePrefix="${timestamp} ${messagePrefix}" ;;
*) ;;
esac
## 4. prefix message with script name + pid?
case ${__PrintPrefixScriptNamePid:-1} in
1) messagePrefix="${__ScriptName:-${0##*/}}[${$}] ${messagePrefix}" ;;
*) ;;
esac
## print message
case ${stderr} in
## print message to stdout
0)
if [[ ${colorStdout} -eq 1 ]]; then
## print colored message
echo -e "\033[${color}m${messagePrefix}${message}\033[m"
else
## print plain message
echo "${messagePrefix}${message}"
fi
;;
## print message to stderr
1)
if [[ ${colorStderr} -eq 1 ]]; then
## print colored message
echo -e "\033[${color}m${messagePrefix}${message}\033[m" 1>&2
else
## print plain message
echo "${messagePrefix}${message}" 1>&2
fi
;;
esac
return 0 # success
} # __msgPrint()
function __print() {
## ----- head -----
##
## DESCRIPTION:
## prints a message
##
## ARGUMENTS:
## 1: severity (req): severity of the message
## 2: message (req): the message to print
##
## GLOBAL VARIABLES USED:
## __MsgTimestampFormat
##
local severity="${1}"; shift
local message="${1}"; shift
## ----- main -----
## get current timestamp
local timestamp=$(date "+${__MsgTimestampFormat:-%Y-%m-%d %H:%M:%S %:z}" 2>/dev/null)
## print message
__msgPrint "${timestamp}" "${severity}" "" "${message}"
return 0 # success
} # __print()
function __msgLog() {
## ----- head -----
##
## DESCRIPTION:
## logs a message (or stdin).
## this function is NOT intended to be called by the user!
##
## ARGUMENTS:
## 1: timestamp (req): timestamp of the message
## 2: severity (req): severity of the message
## 3: source (req): source of the message (file, line, function)
## 4: message (opt): the message to log (else stdin is read and logged)
##
## GLOBAL VARIABLES USED:
## __LogDebug (default: 0)
## __LogInfo (default: 1)
## __LogNotice (default: 1)
## __LogWarning (default: 1)
## __LogErr (default: 1)
## __LogCrit (default: 1)
## __LogAlert (default: 1)
## __LogEmerg (default: 1)
## __LogPrefixScriptNamePid (default: 1)
## __LogPrefixTimestamp (default: 1)
## __LogPrefixSeverity (default: 1)
## __LogPrefixSource (default: 1)
## __LogPrefixSeverity7 (default: >>> [____DEBUG])
## __LogPrefixSeverity6 (default: >>> [_____INFO])
## __LogPrefixSeverity5 (default: >>> [___NOTICE])
## __LogPrefixSeverity4 (default: !!! [__WARNING])
## __LogPrefixSeverity3 (default: !!! [____ERROR])
## __LogPrefixSeverity2 (default: !!! [_CRITICAL])
## __LogPrefixSeverity1 (default: !!! [____ALERT])
## __LogPrefixSeverity0 (default: !!! [EMERGENCY])
## __LogTarget (fallback: syslog.user)
## __LogFileHasBeenWrittenTo (helper variable)
## _L
##
local timestamp="${1}"; shift
local severity="${1}"; shift
local source="${1}"; shift
local message="${1}"; shift
## ----- main -----
## check whether message is to be logged at all
case ${severity} in
debug|7) if [[ ${__LogDebug:-0} -ne 1 ]]; then return 0; fi ;;
info|6) if [[ ${__LogInfo:-1} -ne 1 ]]; then return 0; fi ;;
notice|5) if [[ ${__LogNotice:-1} -ne 1 ]]; then return 0; fi ;;
warning|4) if [[ ${__LogWarning:-1} -ne 1 ]]; then return 0; fi ;;
err|3) if [[ ${__LogErr:-1} -ne 1 ]]; then return 0; fi ;;
crit|2) if [[ ${__LogCrit:-1} -ne 1 ]]; then return 0; fi ;;
alert|1) if [[ ${__LogAlert:-1} -ne 1 ]]; then return 0; fi ;;
emerg|0) if [[ ${__LogEmerg:-1} -ne 1 ]]; then return 0; fi ;;
esac
## mapping severity -> severityPrefix
local severityPrefix
case ${severity} in
debug|7) severityPrefix="${__LogPrefixSeverity7:->>> [____DEBUG]}" ;;
info|6) severityPrefix="${__LogPrefixSeverity6:->>> [_____INFO]}" ;;
notice|5) severityPrefix="${__LogPrefixSeverity5:->>> [___NOTICE]}" ;;
warning|4) severityPrefix="${__LogPrefixSeverity4:-!!! [__WARNING]}" ;;
err|3) severityPrefix="${__LogPrefixSeverity3:-!!! [____ERROR]}" ;;
crit|2) severityPrefix="${__LogPrefixSeverity2:-!!! [_CRITICAL]}" ;;
alert|1) severityPrefix="${__LogPrefixSeverity1:-!!! [____ALERT]}" ;;
emerg|0) severityPrefix="${__LogPrefixSeverity0:-!!! [EMERGENCY]}" ;;
esac
##
## final message structure in order (components can be disabled):
## timestamp severityPrefix source message
##
## we have to use different prefixes for file and syslog targets)
local fileTargetMessagePrefix syslogTargetMessagePrefix
## 1. prefix message with source? (for file and syslog targets)
if [[ -n ${source} ]]; then
case ${__LogPrefixSource:-1} in
1) fileTargetMessagePrefix="${source}: ${fileTargetMessagePrefix}"
syslogTargetMessagePrefix="${source}: ${syslogTargetMessagePrefix}" ;;
*) ;;
esac
fi
## 2. prefix message with severity? (for file target only)
case ${__LogPrefixSeverity:-1} in
1) fileTargetMessagePrefix="${severityPrefix} ${fileTargetMessagePrefix}" ;;
*) ;;
esac
## 3. prefix message with timestamp? (for file target only)
case ${__LogPrefixTimestamp:-1} in
1) fileTargetMessagePrefix="${timestamp} ${fileTargetMessagePrefix}" ;;
*) ;;
esac
## 4. prefix message with script name + pid? (for file target only)
case ${__LogPrefixScriptNamePid:-1} in
1) fileTargetMessagePrefix="${__ScriptName:-${0##*/}}[${$}] ${fileTargetMessagePrefix}" ;;
*) ;;
esac
## loop through list of log targets
IFS=','
local -a logTargetArray=( ${__LogTarget:-syslog:user} )
unset IFS
local -i l=0
for ((l = 0; l < ${#logTargetArray[@]}; l++)); do
local logTarget=${logTargetArray[l]}
case ${logTarget} in
## log to a file
file:*)
## parse log target setting
IFS=':'
set -- ${logTarget}
unset IFS
local logFile=${2} # /path/to/logfile
local logMode=${3:-overwrite} # overwrite|append, default: overwrite
set --
## write log message to file
## if message is empty, we read stdin
if [[ -z ${message} ]]; then
if [[ ${logMode} == 'append' || ${__LogFileHasBeenWrittenTo} -eq 1 ]]; then
## TODO FIXME: check return value?
sed -e "s/^/${fileTargetMessagePrefix}/" >>${logFile} 2>>"${_L:-/dev/null}"
else
## TODO FIXME: check return value?
sed -e "s/^/${fileTargetMessagePrefix}/" >${logFile} 2>>"${_L:-/dev/null}"
fi
else
if [[ ${logMode} == 'append' || ${__LogFileHasBeenWrittenTo} -eq 1 ]]; then
## TODO FIXME: check return value?
echo "${fileTargetMessagePrefix}${message}" >>${logFile} 2>>"${_L:-/dev/null}"
else
## TODO FIXME: check return value?
echo "${fileTargetMessagePrefix}${message}" >${logFile} 2>>"${_L:-/dev/null}"
fi
fi
## global helper variable to determine if logfile
## has already been opened / written to before
## during the current execution of the script,
## needed to support "append" mode.
declare -i __LogFileHasBeenWrittenTo=1
;;
## log via syslog
syslog:*)
## parse log target setting
IFS=':'
set -- ${logTarget}
unset IFS
local syslogFacility=${2:-user}
local syslogPri="${syslogFacility}.${severity}"
local syslogTag="${__ScriptName:-${0##*/}}[${$}]" # scriptname[PID]
set --
## send log message to syslog
if [[ -z ${message} ]]; then
## log stdin
logger -p "${syslogPri}" -t "${syslogTag}" >>"${_L:-/dev/null}" 2>&1
else
## log passed message
logger -p "${syslogPri}" -t "${syslogTag}" -- "${syslogTargetMessagePrefix}${message}" >>"${_L:-/dev/null}" 2>&1
fi
;;
## any other (invalid) log target
*)
return 2 # error
;;
esac
done
return 0 # success
} # __msgLog()
function __log() {
## ----- head -----
##
## DESCRIPTION:
## logs a message (or stdin).
##
## ARGUMENTS:
## 1: severity (req): severity of the message
## 2: message (opt): the message to log (else stdin is read and logged)
##
## GLOBAL VARIABLES USED:
## __MsgTimestampFormat
##
local severity="${1}"; shift
local message="${1}"; shift
## ----- main -----
## get current timestamp
local timestamp=$(date "+${__MsgTimestampFormat:-%Y-%m-%d %H:%M:%S %:z}" 2>/dev/null)
## log message
__msgLog "${timestamp}" "${severity}" "" "${message}"
return 0 # success
} # __log()
function __msg() {
## ----- head -----
##
## DESCRIPTION:
## processes a message (or stdin) for logging/printing/later mailing.
##
## ARGUMENTS:
## 0: -q (opt): quiet (do not print message, required for print functions)
## 1: severity (req): severity of the message
## 2: message (opt): the message to log (else stdin is read and logged)
##
## GLOBAL VARIABLES USED:
## __MsgArray
## __MsgQuiet
## __MsgTimestampFormat
##
local quiet=0
if [[ ${1} == "-q" ]]; then
let quiet=1; shift
fi
local severity="${1}"; shift
local message="${1}"; shift
## ----- main -----
## get current timestamp
local timestamp=$(date "+${__MsgTimestampFormat:-%Y-%m-%d %H:%M:%S %:z}" 2>/dev/null)
## check for global quiet operation setting
if [[ ${__MsgQuiet} -eq 1 ]]; then
let quiet=1
fi
## determine the line number and file name
## of the current script file and the
## calling function
local callingFunction=
local -i bashLineNumber=0
local bashFileName=
case "${FUNCNAME[1]}" in
## we were called by __die()
__die)
## use the info of the function that called __die()
bashFileName=${BASH_SOURCE[2]} # the file name where the function that called __die was called
let bashLineNumber=${BASH_LINENO[1]} # the line number where __die was called
callingFunction=${FUNCNAME[2]} # the name of the function that called __die
;;
## we were called by any other function
*)
## use the info of the function that called __msg()
bashFileName=${BASH_SOURCE[1]} # the file name where the function that called __msg was called
let bashLineNumber=${BASH_LINENO[0]} # the line number where __msg was called
callingFunction=${FUNCNAME[1]} # the name of the function that called __msg
;;
esac
bashFileName=${bashFileName##*/} # strip leading path
## build message source string based on calling function
local source=
case "${callingFunction}" in