functions.sh 1.03 KB
Newer Older
1
2
3
4
5
6
#!/bin/bash

###############################################################################
# Helper functions
###############################################################################

7
8
9
10
11
# colors
yellow='\[\033[0;33m\]'
red='\[\033[0;31m\]'
reset='\[\033[0m\]'

12
13
14
# http://stackoverflow.com/a/25515370
yell() { echo "$0: $*" >&2; }
die() { yell "$*"; exit 111; }
15
try() { "$@" || die "cannot $*"; }
16

17
err() {
18
19
20
21
  echo
  echo ${red}ERROR: ${@}$reset
  echo
  exit 1
22
23
}

24
err_report() {
25
  echo "$1: error on line $2"
26
27
28
}

trap_errors() {
Christopher Pauley's avatar
Christopher Pauley committed
29
30
31
32
  if [ "$debug_scripts" = "true" ]; then
    set -x
  fi

33
34
35
  set -eeuo pipefail
  trap 'err_report $BASH_SOURCE $LINENO' err
  export shellopts
36
37
38
39
}

# check if a variable is set. useful for set -u
is_set() {
40
  declare -p $1 &> /dev/null
41
42
43
44
}

# is the variable set and have length?
not_empty_var() {
45
  is_set $1 && eval val=\$$1 && [[ "$val" ]]
46
47
48
49
50
51
}

# is the variable unset or zero length? useful for set -u
empty_var() {
   ! not_empty_var $1
}
52
53

export -f yell die try err err_report trap_errors is_set not_empty_var empty_var