-
Notifications
You must be signed in to change notification settings - Fork 0
/
simbashlog.bash
3870 lines (3368 loc) · 155 KB
/
simbashlog.bash
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
#!/usr/bin/env bash
# # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# _ _ _ _ #
# (_) | | | | | | #
# ___ _ _ __ ___ | |__ __ _ ___| |__ | | ___ __ _ #
# / __| | '_ ` _ \| '_ \ / _` / __| '_ \| |/ _ \ / _` | #
# \__ \ | | | | | | |_) | (_| \__ \ | | | | (_) | (_| | #
# |___/_|_| |_| |_|_.__/ \__,_|___/_| |_|_|\___/ \__, | #
# __/ | #
# |___/ #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# DISCLAIMER:
# Not POSIX conform!
#
#
# DESCRIPTION:
# This script makes it very simple to log your bash scripts and get notified about the log messages.
# It is best that you source this script first with:
#
# ```bash
# source <path>/simbashlog.bash
# ```
#
# `<path>` should be replaced by the actual path where 'simbashlog' is located.
#
# This script can also be called with arguments so that it can also be used by other programming languages such as Python..
#
# e.g.:
# ```bash
# ./simbashlog.bash -a json -s error --message "An error occured" --notifier example-simbashlog-notifier.py
# ```
#
# To summarize briefly:
# Logging is possible in `.log`, `.json` and in the system.
# `.json` logging can lead to loss of performance and is only possible if the `jq` package is installed!
# But, if a notifier is used, it is still best if json logging is active, as this makes it easier to generate the messages.
# It is also possible to use popups for logging if the `yad` or `zenity` package is installed.
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# ░░ ░░
# ░░ ░░
# ░░ LICENSE ░░
# ░░ ░░
# ░░ ░░
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# https://github.com/fuchs-fabian/simbashlog/blob/main/LICENSE
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# ░░ ░░
# ░░ ░░
# ░░ METADATA ░░
# ░░ ░░
# ░░ ░░
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
declare -rx CONST_SIMBASHLOG_VERSION="1.1.3"
declare -rx CONST_SIMBASHLOG_NAME="simbashlog"
declare -rx CONST_SIMBASHLOG_GITHUB_LINK="https://github.com/fuchs-fabian/simbashlog"
declare -rx CONST_SIMBASHLOG_PAYPAL_DONATE_LINK="https://www.paypal.com/donate/?hosted_button_id=4G9X8TDNYYNKG"
declare -rx CONST_SIMBASHLOG_NOTIFIERS_GITHUB_LINK="https://github.com/fuchs-fabian/simbashlog-notifiers"
declare -rx CONST_SIMBASHLOG_LOG_DIR="/tmp/simbashlogs/"
declare -rx CONST_SIMBASHLOG_REQUIRED_EXTERNAL_PACKAGE_FOR_JSON_LOGGING="jq"
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# ░░ ░░
# ░░ ░░
# ░░ DONATE ░░
# ░░ ░░
# ░░ ░░
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
function _show_donate_message {
echo -e "\t┌───────────────────────────────────────────────────────────────────────────────────────┐"
echo -e "\t│ If you like '$CONST_SIMBASHLOG_NAME', please give it a star and consider donating. │"
echo -e "\t│ \u2B50 GitHub: $CONST_SIMBASHLOG_GITHUB_LINK │"
echo -e "\t│ \u2764\uFE0F Donate via PayPal: $CONST_SIMBASHLOG_PAYPAL_DONATE_LINK │"
echo -e "\t└───────────────────────────────────────────────────────────────────────────────────────┘"
}
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# ░░ ░░
# ░░ ░░
# ░░ ELEMENTS FOR COMMENTS ░░
# ░░ ░░
# ░░ ░░
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# | single | double |
# |--------|--------|
# | ─ | ═ |
# | │ | ║ |
# | ┌ | ╔ |
# | └ | ╚ |
# | ┐ | ╗ |
# | ┘ | ╝ |
# | ├ | ╠ |
# | ┤ | ╣ |
# | ┬ | ╦ |
# | ┴ | ╩ |
# | ┼ | ╬ |
# ░
# ▓
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# ░░ ░░
# ░░ ░░
# ░░ DECLARE ░░
# ░░ ░░
# ░░ ░░
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# declare ...
#
# | Option | Description |
# |--------|------------------------------------------------------------------------------------------------------------------------------------------------|
# | `-a` | Declares a variable as an indexed array. |
# | `-A` | Declares a variable as an associative array. |
# | `-f` | Lists the names and definitions of functions. |
# | `-F` | Lists only the names of functions without their definitions. |
# | `-g` | Declares a global variable within a function (for Bash 4.2 and later). |
# | `-i` | Declares a variable as an integer. Arithmetic operations can be performed directly on the variable. |
# | `-I` | Available in some Bash versions, sets the default content for the function stack (rarely used). |
# | `-l` | Converts the variable to lowercase when its value is assigned. |
# | `-n` | Declares a nameref, a reference to another variable. The referenced variable takes the value of the referencing variable. |
# | `-r` | Declares a variable as readonly. The value of the variable cannot be changed after its declaration. |
# | `-t` | Marks the variable to trigger the DEBUG trap or RETURN trap when the function exits (used for debugging, rarely used). |
# | `-u` | Converts the variable to uppercase when its value is assigned. |
# | `-x` | Exports the variable so that it is available in subprocesses. |
# | `-p` | Returns the attributes and values of declared variables. If no variable is specified, it returns all declared variables with their attributes. |
# ```bash
# declare -rx CONST_MY_CONSTANT="This is a constant"
# ```
#
# Is equivalent to:
#
# ```bash
# readonly CONST_MY_CONSTANT="This is a constant"
# export CONST_MY_CONSTANT
# ```
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# ░░ ░░
# ░░ ░░
# ░░ VARIABLES FOR THE USER ░░
# ░░ ░░
# ░░ ░░
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# ╔═════════════════════╦══════════════════════╗
# ║ ║
# ║ IMMUTABLE VARIABLES ║
# ║ ║
# ╚═════════════════════╩══════════════════════╝
declare -rx CONST_CURRENT_PID="${$}"
declare -rx CONST_SCRIPT_NAME_WITH_CURRENT_PATH="$0"
CONST_SIMPLE_SCRIPT_NAME="$(basename "$CONST_SCRIPT_NAME_WITH_CURRENT_PATH")"
declare -rx CONST_SIMPLE_SCRIPT_NAME
declare -rx CONST_SIMPLE_SCRIPT_NAME_WITHOUT_FILE_EXTENSION="${CONST_SIMPLE_SCRIPT_NAME%.*}"
CONST_ABSOLUTE_SCRIPT_NAME="$(realpath "$CONST_SCRIPT_NAME_WITH_CURRENT_PATH")"
declare -rx CONST_ABSOLUTE_SCRIPT_NAME
CONST_ABSOLUTE_SCRIPT_DIR="$(dirname "$CONST_ABSOLUTE_SCRIPT_NAME")/"
declare -rx CONST_ABSOLUTE_SCRIPT_DIR
# ╔═════════════════════╦══════════════════════╗
# ║ ║
# ║ MUTABLE VARIABLES ║
# ║ ║
# ╚═════════════════════╩══════════════════════╝
# [INFO] The following variables can be overwritten.
# ┌─────────────────────┬──────────────────────┐
# │ BEFORE SOURCING │
# └─────────────────────┴──────────────────────┘
# true: Enables the trap for 'DEBUG'.
#
# This logs all commands as debug messages before they are executed.
# It is not recommended under any circumstances if the script is to be used in production.
declare -xr ENABLE_TRAP_FOR_DEBUG="${ENABLE_TRAP_FOR_DEBUG:=false}"
# true: Enables the trap for 'EXIT'.
#
# If it is desired to use a separate trap for exit in a script that sources simbashlog, this should be set to false.
# Otherwise it can lead to unexpected problems.
declare -xr ENABLE_TRAP_FOR_EXIT="${ENABLE_TRAP_FOR_EXIT:=true}"
# ┌─────────────────────┬──────────────────────┐
# │ BEFORE AND AFTER SOURCING │
# └─────────────────────┴──────────────────────┘
# [INFO] The following variables can be overwritten before or after sourcing.
# true: Enables creation of `.log` files for logging.
declare -x ENABLE_LOG_FILE="${ENABLE_LOG_FILE:=true}"
# true: Enables creation of `.json` files for logging.
declare -x ENABLE_JSON_LOG_FILE="${ENABLE_JSON_LOG_FILE:=false}"
# true: Enables logging with `logger` to system.
declare -x ENABLE_LOG_TO_SYSTEM="${ENABLE_LOG_TO_SYSTEM:=false}"
# Location where the log files are to be stored.
#
# Default structure:
#
# Script 1: `/bin/script1.sh`
# Script 2: `/home/test/script1.sh`
# Script 3: `/home/test/script2.sh`
#
# /tmp/simbashlogs/ -> `LOG_DIR`
# │
# ├── bin/
# │ │
# │ └── script1/ -> log-files
# │
# └── home/test/
# │
# ├── script1/ -> log-files
# │
# └── script2/ -> log-files
declare -x LOG_DIR="${LOG_DIR:="$CONST_SIMBASHLOG_LOG_DIR"}"
# Simplifies the structure where the log files are to be stored in the `LOG_DIR`.
#
# Attention: For scripts with the same name, the messages are written to the same log files.
# Tip: If this is to be used, adjust `LOG_DIR`.
#
# Simplified structure:
#
# Script 1: `/bin/script1.sh`
# Script 2: `/home/test/script1.sh`
# Script 3: `/home/test/script2.sh`
#
# /tmp/simbashlogs/ -> `LOG_DIR`
# │
# ├── script1/ -> log-files
# │
# └── script2/ -> log-files
declare -x ENABLE_SIMPLE_LOG_DIR_STRUCTURE="${ENABLE_SIMPLE_LOG_DIR_STRUCTURE:=true}"
# Combines the log messages in the `LOG_DIR`: Files, with all log messages and files for each severity.
#
# The files for the severities are only created if something has also been logged at this level.
#
# /tmp/simbashlogs/ -> `LOG_DIR`
# │
# ├── combined.log -> `ENABLE_LOG_FILE=true`
# ├── combined_log.json -> `ENABLE_JSON_LOG_FILE=true`
# │
# │
# ├── emerg.log -> `ENABLE_LOG_FILE=true`
# ├── emerg_log.json -> `ENABLE_JSON_LOG_FILE=true`
# │
# ├── alert.log -> `ENABLE_LOG_FILE=true`
# ├── alert_log.json -> `ENABLE_JSON_LOG_FILE=true`
# │
# ├── crit.log -> `ENABLE_LOG_FILE=true`
# ├── crit_log.json -> `ENABLE_JSON_LOG_FILE=true`
# │
# ├── error.log -> `ENABLE_LOG_FILE=true`
# ├── error_log.json -> `ENABLE_JSON_LOG_FILE=true`
# │
# ├── warn.log -> `ENABLE_LOG_FILE=true`
# ├── warn_log.json -> `ENABLE_JSON_LOG_FILE=true`
# │
# ├── notice.log -> `ENABLE_LOG_FILE=true`
# ├── notice_log.json -> `ENABLE_JSON_LOG_FILE=true`
# │
# ├── info.log -> `ENABLE_LOG_FILE=true`
# ├── info_log.json -> `ENABLE_JSON_LOG_FILE=true`
# │
# ├── debug.log -> `ENABLE_LOG_FILE=true`
# └── debug_log.json -> `ENABLE_JSON_LOG_FILE=true`
declare -x ENABLE_COMBINED_LOG_FILES="${ENABLE_COMBINED_LOG_FILES:=false}"
# The log level controls the severity of messages that will be logged.
# Messages at the specified level and all levels with a lower numerical code (i.e., more severe) will be logged.
#
# Log levels (RFC 5424) and the corresponding messages:
#
# | Log level | Severity | Logged Messages |
# |-----------|---------------|-----------------------------------------------------------------------------------------------|
# | `0` | Emergency | Only Emergency messages will be logged. |
# | `1` | Alert | Emergency and Alert messages will be logged. |
# | `2` | Critical | Emergency, Alert and Critical messages will be logged. |
# | `3` | Error | Emergency, Alert, Critical and Error messages will be logged. |
# | `4` | Warning | Emergency, Alert, Critical, Error and Warning messages will be logged. |
# | `5` | Notice | Emergency, Alert, Critical, Error, Warning and Notice messages will be logged. |
# | `6` | Informational | Emergency, Alert, Critical, Error, Warning, Notice and Informational messages will be logged. |
# | `7` | Debug | All messages, including Debug-level, will be logged. |
declare -x LOG_LEVEL="${LOG_LEVEL:=6}"
declare -x LOG_LEVEL_FOR_SYSTEM_LOGGING="${LOG_LEVEL_FOR_SYSTEM_LOGGING:=4}"
# Valid Facility Names (from the `logger` man page)
#
# | Valid Facility Name | Additional Information |
# |---------------------|-------------------------------------------------------------------------------|
# | `auth` | |
# | `authpriv` | For security information of a sensitive nature |
# | `cron` | |
# | | |
# | `daemon` | |
# | `ftp` | |
# | `kern` | Cannot be generated from userspace process, automatically converted to `user` |
# | | |
# | `lpr` | |
# | `mail` | |
# | `news` | |
# | `syslog` | |
# | `user` | |
# | `uucp` | |
# | `local0` | |
# | `local1` | |
# | `local2` | |
# | `local3` | |
# | `local4` | |
# | `local5` | |
# | `local6` | |
# | `local7` | |
# | `security` | Deprecated synonym for `auth` |
declare -x FACILITY_NAME_FOR_SYSTEM_LOGGING="${FACILITY_NAME_FOR_SYSTEM_LOGGING:="user"}"
# true: The script will exit if any message of severity Error (3) or higher (i.e., lower numerical code) is logged.
declare -x ENABLE_EXITING_SCRIPT_IF_AT_LEAST_ERROR_IS_LOGGED="${ENABLE_EXITING_SCRIPT_IF_AT_LEAST_ERROR_IS_LOGGED:=false}"
# true: `<date> - [<level>] - <message>`
# false: `[<level>] - <message>`
declare -x ENABLE_DATE_IN_CONSOLE_OUTPUTS_FOR_LOGGING="${ENABLE_DATE_IN_CONSOLE_OUTPUTS_FOR_LOGGING:=false}"
# "path": `CONST_SCRIPT_NAME_WITH_CURRENT_PATH`
# "simple": `CONST_SIMPLE_SCRIPT_NAME`
# "simple_without_file_extension": `CONST_SIMPLE_SCRIPT_NAME_WITHOUT_FILE_EXTENSION`
# "absolute": `CONST_ABSOLUTE_SCRIPT_NAME`
#
# Example: `[<script name>] - [<level>] - <message>`
# If the script is located at `/home/user/scripts/myscript.sh` and is executed with different methods:
# - "path": If executed as `/home/user/scripts/myscript.sh`, the output will be `/home/user/scripts/myscript.sh`.
# If executed as `./myscript.sh` from the script's directory, the output will be `./myscript.sh`.
# - "simple": `myscript.sh`
# - "simple_without_file_extension": `myscript`
# - "absolute": `/home/user/scripts/myscript.sh`
declare -x SHOW_CURRENT_SCRIPT_NAME_IN_CONSOLE_OUTPUTS_FOR_LOGGING="${SHOW_CURRENT_SCRIPT_NAME_IN_CONSOLE_OUTPUTS_FOR_LOGGING:="path"}"
# If set (-> not "" or defined in the script, that sources 'simbashlog'), this value will be used in the folder structure for log file organization.
# The log data will first be written in a folder named after the parent script's directory, before falling back to the default log directory structure.
#
# Default behavior:
# The command retrieves the full command-line arguments of the parent process that invoked the current script.
# It then removes any instances of "/bin/bash" and leading "bash " from the command string to clean up the path.
# The result is the absolute path of the parent script, excluding the shell invocation details.
#
# The `realpath` command is used to convert this path to its absolute form.
# If `realpath` fails (e.g., if the path does not exist), an empty string is used.
: "${PARENT_SCRIPT_NAME:="$(realpath "$(ps -o args= -p $PPID | sed -e 's:/bin/bash::g' -e 's:^[[:space:]]*bash ::g')" 2>/dev/null || echo "")"}"
declare -x PARENT_SCRIPT_NAME
# true: Parent script name is included in the console output.
# Note: This is only used if `PARENT_SCRIPT_NAME` is not empty.
#
# Example: `[<parent script name> -> <script name>] - [<level>] - <message>`
declare -x ENABLE_PARENT_SCRIPT_NAME_IN_CONSOLE_OUTPUTS_FOR_LOGGING="${ENABLE_PARENT_SCRIPT_NAME_IN_CONSOLE_OUTPUTS_FOR_LOGGING:=false}"
# This flag controls whether GUI popups are used for logging notifications.
# When set to true:
# - If `yad` (Yet Another Dialog) is installed, it will be used to display the notifications.
# - If `yad` is not installed, but `zenity` is available, `zenity` will be used as a fallback.
# - If neither `yad` nor `zenity` is installed, no GUI output will be displayed.
# When set to false, no GUI popups will be used for logging notifications, regardless of whether `yad` or `zenity` is installed.
declare -x ENABLE_GUI_POPUPS_FOR_LOGGING_NOTIFICATIONS="${ENABLE_GUI_POPUPS_FOR_LOGGING_NOTIFICATIONS:=false}"
# IMPORTANT:
# - If the script is called with arguments, the parent script name is the name used for the logic!
# - If the parent script name is empty, the script name is used for the log actions except for console outputs.
# These settings control the dimensions of the popup window that displays log notifications to the user.
declare -x LOG_POPUP_NOTIFICATION_WINDOW_WIDTH="${LOG_POPUP_NOTIFICATION_WINDOW_WIDTH:=500}"
declare -x LOG_POPUP_NOTIFICATION_WINDOW_HEIGHT="${LOG_POPUP_NOTIFICATION_WINDOW_HEIGHT:=100}"
# This parameter defines the name of the script that acts as the notifier.
# It must accept the following arguments:
# --config: The path to the configuration file.
# --pid: The process ID.
# --log-level: A number specifying the desired log level.
# --message: The message to be displayed. Only used when script is called with arguments.
# --log-file: The `*.log`` file.
# --json-log-file: The `*_log.json` log file
#
# The notifier sends notifications based on the methods defined in the notifier script.
# If `SIMBASHLOG_NOTIFIER` is empty, no notifications will be sent.
declare -x SIMBASHLOG_NOTIFIER="${SIMBASHLOG_NOTIFIER:=""}"
# This parameter defines the configuration file for the notifier.
declare -x SIMBASHLOG_NOTIFIER_CONFIG_PATH="${SIMBASHLOG_NOTIFIER_CONFIG_PATH:=""}"
# This flag controls whether the script should display a summary on exit.
declare -x ENABLE_SUMMARY_ON_EXIT="${ENABLE_SUMMARY_ON_EXIT:=false}"
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# ░░ ░░
# ░░ ░░
# ░░ SHELL BEHAVIOR - SET ░░
# ░░ ░░
# ░░ ░░
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# set ...
#
# | Option | Description | Usefulness |
# |----------------|------------------------------------------------------------------|-------------------------------------------------------------------------------------|
# | `-u` | Causes the script to throw an error and | Prevents the use of uninitialized variables, which can lead to unexpected behavior. |
# | | exit if an uninitialized variable is used. | |
# | `-o pipefail` | Causes the script to fail if any command in a pipeline fails. | Ensures that errors in a pipeline are not ignored. |
# | `-e` | Causes the script to exit immediately if | Prevents the script from continuing after a critical error. |
# | | any command exits with a non-zero status. | |
# | `-x` | Prints each command and its arguments to the console | Useful for debugging to trace the commands and the flow of the script. |
# | | before executing it. | |
# | `-v` | Prints each line of the script, including blank lines | Tracks the detailed flow of the script, including comments and blank lines. |
# | | and comments, before executing it. | |
# | `+e`/`+x` | Disables the corresponding option (`-e`, `-x`, `-u`, `-v`). | Temporarily turns off specific `set` options. |
# | `-o` | Shows the current status of all options (enabled or disabled). | Checks which `set` options are currently active. |
# | `-o ignoreeof` | Prevents the script from exiting when `Ctrl+D` (EOF) is pressed. | Prevents accidental script termination by `Ctrl+D`. |
# | `-o noclobber` | Prevents files from being overwritten by redirection (`> file`). | Prevents accidental overwriting of files. |
# | | If the file exists, it will result in an error. | |
set -uo pipefail
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# ░░ ░░
# ░░ ░░
# ░░ COLOR UTILS ░░
# ░░ ░░
# ░░ ░░
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# ╔═════════════════════╦══════════════════════╗
# ║ ║
# ║ ANSI COLORS ║
# ║ ║
# ╚═════════════════════╩══════════════════════╝
# https://gist.github.com/JBlond/2fea43a3049b38287e5e9cefc87b2124#file-bash-colors-md
#
# | | regular | bold | underline | background | high_intensity | bold_high_intensity | high_intensity_background |
# |----------|----------|----------|------------|------------|----------------|---------------------|---------------------------|
# | black | \e[0;30m | \e[1;30m | \e[4;30m | \e[40m | \e[0;90m | \e[1;90m | \e[0;100m |
# | red | \e[0;31m | \e[1;31m | \e[4;31m | \e[41m | \e[0;91m | \e[1;91m | \e[0;101m |
# | green | \e[0;32m | \e[1;32m | \e[4;32m | \e[42m | \e[0;92m | \e[1;92m | \e[0;102m |
# | yellow | \e[0;33m | \e[1;33m | \e[4;33m | \e[43m | \e[0;93m | \e[1;93m | \e[0;103m |
# | blue | \e[0;34m | \e[1;34m | \e[4;34m | \e[44m | \e[0;94m | \e[1;94m | \e[0;104m |
# | purple | \e[0;35m | \e[1;35m | \e[4;35m | \e[45m | \e[0;95m | \e[1;95m | \e[0;105m |
# | cyan | \e[0;36m | \e[1;36m | \e[4;36m | \e[46m | \e[0;96m | \e[1;96m | \e[0;106m |
# | white | \e[0;37m | \e[1;37m | \e[4;37m | \e[47m | \e[0;97m | \e[1;97m | \e[0;107m |
# | reset | \e[0m | - | - | - | - | - | - |
declare -Arx CONST_ANSI_COLORS=(
[black, regular]='\e[0;30m'
[black, bold]='\e[1;30m'
[black, underline]='\e[4;30m'
[black, background]='\e[40m'
[black, high_intensity]='\e[0;90m'
[black, bold_high_intensity]='\e[1;90m'
[black, high_intensity_background]='\e[0;100m'
[red, regular]='\e[0;31m'
[red, bold]='\e[1;31m'
[red, underline]='\e[4;31m'
[red, background]='\e[41m'
[red, high_intensity]='\e[0;91m'
[red, bold_high_intensity]='\e[1;91m'
[red, high_intensity_background]='\e[0;101m'
[green, regular]='\e[0;32m'
[green, bold]='\e[1;32m'
[green, underline]='\e[4;32m'
[green, background]='\e[42m'
[green, high_intensity]='\e[0;92m'
[green, bold_high_intensity]='\e[1;92m'
[green, high_intensity_background]='\e[0;102m'
[yellow, regular]='\e[0;33m'
[yellow, bold]='\e[1;33m'
[yellow, underline]='\e[4;33m'
[yellow, background]='\e[43m'
[yellow, high_intensity]='\e[0;93m'
[yellow, bold_high_intensity]='\e[1;93m'
[yellow, high_intensity_background]='\e[0;103m'
[blue, regular]='\e[0;34m'
[blue, bold]='\e[1;34m'
[blue, underline]='\e[4;34m'
[blue, background]='\e[44m'
[blue, high_intensity]='\e[0;94m'
[blue, bold_high_intensity]='\e[1;94m'
[blue, high_intensity_background]='\e[0;104m'
[purple, regular]='\e[0;35m'
[purple, bold]='\e[1;35m'
[purple, underline]='\e[4;35m'
[purple, background]='\e[45m'
[purple, high_intensity]='\e[0;95m'
[purple, bold_high_intensity]='\e[1;95m'
[purple, high_intensity_background]='\e[0;105m'
[cyan, regular]='\e[0;36m'
[cyan, bold]='\e[1;36m'
[cyan, underline]='\e[4;36m'
[cyan, background]='\e[46m'
[cyan, high_intensity]='\e[0;96m'
[cyan, bold_high_intensity]='\e[1;96m'
[cyan, high_intensity_background]='\e[0;106m'
[white, regular]='\e[0;37m'
[white, bold]='\e[1;37m'
[white, underline]='\e[4;37m'
[white, background]='\e[47m'
[white, high_intensity]='\e[0;97m'
[white, bold_high_intensity]='\e[1;97m'
[white, high_intensity_background]='\e[0;107m'
[reset, regular]='\e[0m'
)
declare -rx CONST_COLOR_CODE_FOR_RESETTING_FOREGROUND_AND_BACKGROUND="${CONST_ANSI_COLORS[reset, regular]}${CONST_ANSI_COLORS[reset, regular]}"
# ╔═════════════════════╦══════════════════════╗
# ║ ║
# ║ STDERR ║
# ║ ║
# ╚═════════════════════╩══════════════════════╝
# Prints an error message to stderr, with optional severity-based coloring.
#
# Parameters:
# $1 - The error message to be printed. This is a required parameter.
# $2 - (Optional) The severity of the message. Can be "error" or "warn".
# If "error", the message is printed in red and bold.
# If "warn", the message is printed in yellow and bold.
# If not provided or any other value, the message is printed without color.
#
# Example:
# print_stderr "An unexpected error occurred." "error"
# print_stderr "This is a warning." "warn"
# print_stderr "This is a regular stderr message without color."
function print_stderr {
local stderr_message="${1:-}"
local severity="${2:-}"
if [[ -z "$stderr_message" ]]; then
echo "[!] The stderr message to be printed is empty!" >&2
ENABLE_SUMMARY_ON_EXIT=false
exit 1
fi
local message
case "$severity" in
error)
message="${CONST_ANSI_COLORS[red, bold]}${stderr_message}"
;;
warn)
message="${CONST_ANSI_COLORS[yellow, bold]}${stderr_message}"
;;
*)
echo "$stderr_message" >&2
return 0
;;
esac
echo -e "${CONST_COLOR_CODE_FOR_RESETTING_FOREGROUND_AND_BACKGROUND}${message}${CONST_COLOR_CODE_FOR_RESETTING_FOREGROUND_AND_BACKGROUND}" >&2
return 0
}
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# ░░ ░░
# ░░ ░░
# ░░ VALIDATION OF VARIABLE TYPES ░░
# ░░ ░░
# ░░ ░░
# ░░░░░░░░░░░░░░░░░░░░░▓▓▓░░░░░░░░░░░░░░░░░░░░░░
# ╔═════════════════════╦══════════════════════╗
# ║ ║
# ║ SIMPLE VARIABLE TYPES ║
# ║ ║
# ╚═════════════════════╩══════════════════════╝
# ┌─────────────────────┬──────────────────────┐
# │ RAW VARIABLES │
# └─────────────────────┴──────────────────────┘
# Checks if the specified variable is empty.
#
# Parameters:
# $1 - The value to check (variable or string).
#
# Returns:
# 0 if the variable is empty or unset.
# 1 if the variable has a non-empty value.
#
# Example:
# my_var=""
# if is_var_empty "$my_var"; then
# echo "Is empty."
# else
# echo "Is not empty."
# fi
function is_var_empty {
if [[ -z "$1" ]]; then
return 0
else
return 1
fi
}
# Works like `is_var_empty`, but negates the output.
function is_var_not_empty {
! is_var_empty "$1"
}
# Checks if the specified variable is equal to another variable.
#
# Parameters:
# $1 - The first variable to compare (string).
# $2 - The second variable to compare (string).
#
# Returns:
# 0 if the variables are equal.
# 1 if the variables are not equal.
#
# Example:
# var1="value"
# var2="value"
# if is_var_equal "$var1" "$var2"; then
# echo "Variables are equal."
# else
# echo "Variables are not equal."
# fi
function is_var_equal {
if [[ "$1" == "$2" ]]; then
return 0
else
return 1
fi
}
# Works like `is_var_equal`, but negates the output.
function is_var_not_equal {
! is_var_equal "$1" "$2"
}
# ┌─────────────────────┬──────────────────────┐
# │ BOOLEANS │
# └─────────────────────┴──────────────────────┘
# Checks if the specified value is a boolean (either "true" or "false").
#
# Parameters:
# $1 - The value to check (string).
#
# Returns:
# 0 if the value is "true" or "false".
# 1 if the value is neither "true" nor "false".
#
# Example:
# value=true
# if is_boolean "$value"; then
# echo "Value is a boolean."
# else
# echo "Value is not a boolean."
# fi
function is_boolean {
case "$1" in
true | false)
return 0
;;
*)
return 1
;;
esac
}
# Works like `is_boolean`, but negates the output.
function is_not_boolean {
! is_boolean "$1"
}
# Checks if the specified boolean value is "true".
#
# Parameters:
# $1 - The value to check (string).
#
# Returns:
# 0 if the value is "true".
# 1 if the value is not "true".
#
# Example:
# value="true"
# if is_true "$value"; then
# echo "Value is true."
# else
# echo "Value is not true."
# fi
function is_true {
if is_boolean "$1"; then
if is_var_equal "$1" "true"; then
return 0
fi
fi
return 1
}
# Works like `is_true`, but with "false".
function is_false {
if is_boolean "$1"; then
if is_var_equal "$1" "false"; then
return 0
fi
fi
return 1
}
# ┌─────────────────────┬──────────────────────┐
# │ NUMERIC VARIABLES │
# └─────────────────────┴──────────────────────┘
# Checks if the specified value is numeric (consists only of digits).
#
# Parameters:
# $1 - The value to check (string).
#
# Returns:
# 0 if the value is numeric.
# 1 if the value is not numeric.
#
# Example:
# value="123"
# if is_numeric "$value"; then
# echo "Value is numeric."
# else
# echo "Value is not numeric."
# fi
function is_numeric {
if [[ "$1" =~ ^[0-9]+$ ]]; then
return 0
else
return 1
fi
}
# Works like `is_numeric`, but negates the output.
function is_not_numeric {
! is_numeric "$1"
}
function _print_stderr_for_not_numeric {
print_stderr "'$1' is not a numeric value." "warn"
}
# Checks if the specified numeric value is smaller than another numeric value.
#
# Parameters:
# $1 - The value to check (string).
# $2 - The value to compare against (string).
#
# Returns:
# 0 if the value is numeric and smaller than the compared value.
# 1 if a parameter is not numeric, or if the value is not smaller than the compared value.
#
# Example:
# value="5"
# compared_value="10"
# if is_less "$value" "$compared_value"; then
# echo "Value is smaller."
# else
# echo "Value is not smaller."
# fi
function is_less {
local value="$1"
local compared_value="$2"
if is_not_numeric "$value"; then
_print_stderr_for_not_numeric "$value"
return 1
fi
if is_not_numeric "$compared_value"; then
_print_stderr_for_not_numeric "$compared_value"
return 1
fi
if ((value < compared_value)); then
return 0
else
return 1
fi
}
# Works like `is_less`, but also returns true if the values are equal.
function is_less_or_equal {
local value="$1"
local compared_value="$2"
if is_not_numeric "$value"; then
_print_stderr_for_not_numeric "$value"
return 1
fi
if is_not_numeric "$compared_value"; then
_print_stderr_for_not_numeric "$compared_value"
return 1
fi
if ((value <= compared_value)); then
return 0
else
return 1
fi
}
# Works like `is_less`, but checks if the value is bigger than the compared value.
function is_greater {
local value="$1"
local compared_value="$2"
if is_not_numeric "$value"; then
_print_stderr_for_not_numeric "$value"
return 1
fi
if is_not_numeric "$compared_value"; then
_print_stderr_for_not_numeric "$compared_value"
return 1
fi
if ((value > compared_value)); then
return 0
else
return 1
fi
}
# Works like `is_greater`, but also returns true if the values are equal.
function is_greater_or_equal {
local value="$1"
local compared_value="$2"
if is_not_numeric "$value"; then
_print_stderr_for_not_numeric "$value"
return 1
fi
if is_not_numeric "$compared_value"; then
_print_stderr_for_not_numeric "$compared_value"
return 1
fi
if ((value >= compared_value)); then
return 0
else
return 1
fi
}
# Checks if the specified numeric value is greater than zero.
#
# Parameters:
# $1 - The value to check (string).
#
# Returns:
# 0 if the value is numeric and greater than zero.
# 1 if the value is not numeric, or if it is numeric but not greater than zero.
#
# Example:
# value="5"
# if is_numeric_and_greater_than_zero "$value"; then
# echo "Value is numeric and greater than zero."
# else
# echo "Value is not numeric or not greater than zero."
# fi
function is_numeric_and_greater_than_zero {
local value="$1"
if is_numeric "$value"; then
if ((value > 0)); then
return 0
else
return 1
fi
else
_print_stderr_for_not_numeric "$value"
return 1
fi
}
# Checks if the specified numeric value is within a given range, inclusive.
#
# Parameters:
# $1 - The value to check (string).
# $2 - The minimum value of the range (string), inclusive.
# $3 - The maximum value of the range (string), inclusive.
#
# Returns:
# 0 if the value is numeric and falls within the specified range (inclusive).
# 1 if a parameter is not numeric, or if it does not fall within the specified range.
#
# Example:
# value="5"
# min="1"
# max="10"
# if is_numeric_in_range "$value" "$min" "$max"; then
# echo "Value is numeric and within the range."
# else
# echo "Value is either not numeric or not within the range."
# fi
function is_numeric_in_range {
local value="$1"
local min="${2:-}" # inclusive
local max="${3:-}" # inclusive
local message_part_for_empty_var=": Is empty! 'is_numeric_in_range' aborted!"
if is_var_empty "$min"; then
print_stderr "'min'$message_part_for_empty_var" "warn"
return 1
fi
if is_var_empty "$max"; then
print_stderr "'max'$message_part_for_empty_var" "warn"
return 1
fi
if is_not_numeric "$value"; then
_print_stderr_for_not_numeric "$value"
return 1
fi
if is_not_numeric "$min"; then
_print_stderr_for_not_numeric "$min"
return 1
fi
if is_not_numeric "$max"; then
_print_stderr_for_not_numeric "$max"
return 1
fi
if ((value >= min && value <= max)); then
return 0
else
return 1
fi
}
# ╔═════════════════════╦══════════════════════╗
# ║ ║
# ║ ADVANCED VARIABLE TYPES ║
# ║ ║
# ╚═════════════════════╩══════════════════════╝
# ┌─────────────────────┬──────────────────────┐
# │ INDEXED ARRAYS │
# └─────────────────────┴──────────────────────┘
# Checks if the specified variable is an indexed array.
#
# Parameters:
# $1 - The name of the indexed array to check (string).
#
# Returns:
# 0 if the variable is declared as an indexed array (i.e., `declare -a`).
# 1 if the variable is not an indexed array or does not exist.
#
# Example:
# my_array=("element1" "element2")
# if is_indexed_array "my_array"; then
# echo "The variable is an indexed array."
# else
# echo "The variable is not an indexed array."
# fi
function is_indexed_array {
local indexed_array_name="$1"
if [[ "$(declare -p "$indexed_array_name" 2>/dev/null)" =~ "declare -a" ]]; then
return 0
else
print_stderr "'$indexed_array_name' was not declared as an indexed ('declare -a $indexed_array_name' or '$indexed_array_name=()') array or does not exist." "warn"
return 1