]> arthur.barton.de Git - ax-unix.git/blob - lib/ax/ax-common.sh
ax-common: Bump API version to 2
[ax-unix.git] / lib / ax / ax-common.sh
1 #!/bin/sh
2 #
3 # ax-common.sh -- Common Functions for Shell Scripts
4 # Copyright (c)2013-2017 Alexander Barton (alex@barton.de)
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11
12 # "ax_common_sourced" is a flag and stores the "API version" of "ax-common.sh",
13 # too. It should be incremented each time the public API changes!
14 # shellcheck disable=SC2034
15 ax_common_sourced=2
16
17 # Display a colored message.
18 #  $1    Level: -=title, 0=ok, 1=warning, 2=error.
19 #  $2    Word(s) to highlight.
20 #  $3-n  Remaining word(s). [optional]
21 ax_msg1() {
22         case "$1" in
23                 "0")    c="32"; shift; ;;       # green
24                 "1")    c="33"; shift; ;;       # yellow
25                 "2")    c="31"; shift; ;;       # red
26                 "-")    c="1";  shift; ;;       # bold
27                 *)      c="0";
28         esac
29         # print colored word(s):
30         printf "\033[0;%sm%s\033[0m " "${c}" "${1}"
31         shift
32         # print remaining word(s) and trailing newline:
33         echo "${*}"
34 }
35
36 # Display a colored message.
37 #  $1    Level, see ax_msg1 function.
38 #  $2-n  Word(s) to highlight.
39 ax_msg() {
40         level="$1"
41         shift
42         ax_msg1 "$level" "$*"
43 }
44
45 # Display an error message to stderr.
46 #  [-l]  Log message to syslog, too.
47 #  $1-n  Error message.
48 ax_error() {
49         if [ "$1" = "-l" ]; then
50                 shift
51                 if [ -n "$NAME" ]; then
52                         logger -t "$NAME" "$*"
53                 else
54                         logger "$*"
55                 fi
56         fi
57         ax_msg1 2 "$*" >&2
58 }
59
60 # Abort the script with an error message and exit code 1.
61 #  [-l]  Log message to syslog, too.
62 #  $1    Error message [optional]. Will be formatted as "Error: %s Aborting!".
63 #        if no error message is given, "Aborting!" will be printed.
64 ax_abort() {
65         if [ "$1" = "-l" ]; then
66                 log_param="-l"
67         else
68                 unset log_param
69         fi
70         if [ $# -gt 0 ]; then
71                 ax_error $log_param "Error: $* Aborting!"
72         else
73                 ax_error $log_param "Aborting!"
74         fi
75         exit 1
76 }
77
78 # Display a debug message, when debug mode is enabled, that is, the environment
79 # variable "DEBUG" is set.
80 ax_debug() {
81         [ -n "$DEBUG" ] && ax_msg1 1 "DEBUG:" "$*"
82 }