diff --git a/lib/sharedFunctions.sh b/lib/sharedFunctions.sh index 2dbb7f0..2a7b567 100755 --- a/lib/sharedFunctions.sh +++ b/lib/sharedFunctions.sh @@ -12,6 +12,7 @@ # # ################################################## + # Traps # ------------------------------------------------------ # These functions are for use with different trap scenarios @@ -376,11 +377,76 @@ function pauseScript() { fi } - - - - - +function in_array() { + # Determine if a value is in an array. + # Usage: in_array [VALUE] [ARRAY] + local value=$1; shift + for item in "$@"; do + [[ $item == $value ]] && return 0 + done + return 1 +} + +# Text Transformations +# ----------------------------------- +# Transform text using these functions. +# Adapted from https://github.com/jmcantrell/bashful +# ----------------------------------- + +lower() { + # Convert stdin to lowercase. + # usage: text=$(lower <<<"$1") + # echo "MAKETHISLOWERCASE" | lower + tr '[:upper:]' '[:lower:]' +} + +upper() { + # Convert stdin to uppercase. + # usage: text=$(upper <<<"$1") + # echo "MAKETHISUPPERCASE" | upper + tr '[:lower:]' '[:upper:]' +} + +ltrim() { + # Removes all leading whitespace (from the left). + local char=${1:-[:space:]} + sed "s%^[${char//%/\\%}]*%%" +} + +rtrim() { + # Removes all trailing whitespace (from the right). + local char=${1:-[:space:]} + sed "s%[${char//%/\\%}]*$%%" +} + +trim() { + # Removes all leading/trailing whitespace + # Usage examples: + # echo " foo bar baz " | trim #==> "foo bar baz" + ltrim "$1" | rtrim "$1" +} + +squeeze() { + # Removes leading/trailing whitespace and condenses all other consecutive + # whitespace into a single space. + # + # Usage examples: + # echo " foo bar baz " | squeeze #==> "foo bar baz" + + local char=${1:-[[:space:]]} + sed "s%\(${char//%/\\%}\)\+%\1%g" | trim "$char" +} + +squeeze_lines() { + # {{{ + # + # Removes all leading/trailing blank lines and condenses all other + # consecutive blank lines into a single blank line. + # + # }}} + + sed '/^[[:space:]]\+$/s/.*//g' | cat -s | trim_lines +}