]> arthur.barton.de Git - ax-unix.git/blob - lib/ax/ax-common.sh
189d7ca20aa6be39122e5e98b00d32d09a08143a
[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-2015 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 # shellcheck disable=SC2034
13 ax_common_sourced=1
14
15 # Display a colored message.
16 #  $1    Level: -=title, 0=ok, 1=warning, 2=error.
17 #  $2    Word(s) to highlight.
18 #  $3-n  Remaining word(s). [optional]
19 ax_msg1() {
20         case "$1" in
21                 "0")    c="32"; shift; ;;       # green
22                 "1")    c="33"; shift; ;;       # yellow
23                 "2")    c="31"; shift; ;;       # red
24                 "-")    c="1";  shift; ;;       # bold
25                 *)      c="0";
26         esac
27         # print colored word(s):
28         printf "\033[0;%sm%s\033[0m " "${c}" "${1}"
29         shift
30         # print remaining word(s) and trailing newline:
31         echo "${*}"
32 }
33
34 # Display a colored message.
35 #  $1    Level, see ax_msg1 function.
36 #  $2-n  Word(s) to highlight.
37 ax_msg() {
38         level="$1"
39         shift
40         ax_msg1 "$level" "$*"
41 }
42
43 # Display an error message to stderr.
44 #  [-l]  Log message to syslog, too.
45 #  $1-n  Error message.
46 ax_error() {
47         if [ "$1" = "-l" ]; then
48                 shift
49                 if [ -n "$NAME" ]; then
50                         logger -t "$NAME" "$*"
51                 else
52                         logger "$*"
53                 fi
54         fi
55         ax_msg1 2 "$*" >&2
56 }
57
58 # Abort the script with an error message and exit code 1.
59 #  [-l]  Log message to syslog, too.
60 #  $1    Error message [optional]. Will be formatted as "Error: %s Aborting!".
61 #        if no error message is given, "Aborting!" will be printed.
62 ax_abort() {
63         if [ "$1" = "-l" ]; then
64                 log_param="-l"
65         else
66                 unset log_param
67         fi
68         if [ $# -gt 0 ]; then
69                 ax_error $log_param "Error: $* Aborting!"
70         else
71                 ax_error $log_param "Aborting!"
72         fi
73         exit 1
74 }
75
76 # Display a debug message, when debug mode is enabled, that is, the environment
77 # variable "DEBUG" is set.
78 ax_debug() {
79         [ -n "$DEBUG" ] && ax_msg1 1 "DEBUG:" "$*"
80 }