]> arthur.barton.de Git - ax-unix.git/blob - lib/ax/ax-common.sh
Add lib/ax/ax-common.sh
[ax-unix.git] / lib / ax / ax-common.sh
1 #
2 # ax-common.sh -- Common Functions for Shell Scripts
3 # Copyright (c)2013-2015 Alexander Barton (alex@barton.de)
4 #
5 # This program is free software; you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 2 of the License, or
8 # (at your option) any later version.
9 #
10
11 ax_common_sourced=1
12
13 # Display a colored message.
14 #  $1    Level: -=title, 0=ok, 1=warning, 2=error.
15 #  $2    Word(s) to highlight.
16 #  $3-n  Remaining word(s). [optional]
17 ax_msg1() {
18         case "$1" in
19                 "0")    c="32"; shift; ;;       # green
20                 "1")    c="33"; shift; ;;       # yellow
21                 "2")    c="31"; shift; ;;       # red
22                 "-")    c="1";  shift; ;;       # bold
23                 *)      c="0";
24         esac
25         # print colored word(s):
26         printf "\x1b[0;${c}m"
27         /bin/echo -n "${1}"
28         printf "\x1b[0m "
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 # Abort the script with an error message and exit code 1.
44 #  $1  Error message [optional]. Will be formatted as "Error: %s Aborting!".
45 #      if no error message is given, "Aborting!" will be printed.
46 ax_abort() {
47         [ $# -gt 0 ] \
48                 && ax_msg 2 "Error: $* Aborting!" \
49                 || ax_msg 2 "Aborting!"
50         exit 1
51 }