You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
113 lines
2.3 KiB
113 lines
2.3 KiB
## library of useful functions, usually prefixed with '_'
|
|
|
|
## ===============
|
|
## ARRAY Functions
|
|
## ===============
|
|
|
|
function _array_contains {
|
|
local -n array=$1
|
|
local element=$2
|
|
[[ " ${array[@]} " =~ " ${element} " ]] && return 0 || return 1
|
|
}
|
|
|
|
function _array_intersect {
|
|
local -n arr1=$1
|
|
local -n arr2=$2
|
|
local -n result=$3
|
|
|
|
declare -A include
|
|
for item in "${arr2[@]}"; do include["$item"]=1; done
|
|
|
|
result=()
|
|
for item in "${arr1[@]}"; do [[ -n ${include["$item"]} ]] && result+=("$item"); done
|
|
}
|
|
|
|
function _array_subtract {
|
|
local -n arr1=$1 # First array
|
|
local -n arr2=$2 # Array to subtract
|
|
local -n result=$3 # Output array
|
|
|
|
[[ ${#arr2[@]} == 0 ]] && result=("${arr1[@]}") && return
|
|
|
|
declare -A exclude
|
|
for item in "${arr2[@]}"; do exclude["$item"]=1; done
|
|
|
|
result=()
|
|
for item in "${arr1[@]}"; do [[ -z ${exclude["$item"]} ]] && result+=("$item"); done
|
|
}
|
|
|
|
## ==============
|
|
## TEXT Functions
|
|
## ==============
|
|
|
|
function _pluralize_simple {
|
|
echo -n "$1 "
|
|
[[ $1 -eq 1 || $1 -eq -1 ]] && echo ${2} || echo ${2}s
|
|
}
|
|
|
|
## ==============
|
|
## READ Functions
|
|
## ==============
|
|
|
|
function _confirm_destructive {
|
|
local message="${1:-This cannot be undone!}"
|
|
echo "⚠️ WARNING: $message"
|
|
read -p "Type YES to confirm: " response
|
|
case "$response" in
|
|
[yY][eE][sS] | [yY]) return 0 ;;
|
|
*) echo "canceled!" && return 1 ;;
|
|
esac
|
|
}
|
|
|
|
## ==============
|
|
## Deprecated: FIXME: to remove
|
|
## ==============
|
|
|
|
##
|
|
# return 0 (true) if array (passed by name) contains element
|
|
# usage:
|
|
# ARRAY=( a b c )
|
|
# containsElement ARRAY 'a' => 0
|
|
function containsElement {
|
|
isArray "$1" || (echo >&2 "ERROR: <$1> not an array!" && return 2)
|
|
array_inter="$1[@]"
|
|
array=("${!array_inter}")
|
|
for i in "${array[@]}"; do [[ "$i" == "$2" ]] && return 0; done
|
|
return 1
|
|
}
|
|
|
|
## return 0 (true) if arg1 (passed by name) is an array
|
|
function isArray {
|
|
[[ "$(declare -p "$1" 2>/dev/null)" =~ "declare -a" ]] || return 1
|
|
}
|
|
|
|
function isDebian {
|
|
grep ^ID=debian /etc/os-release
|
|
}
|
|
|
|
function isArch {
|
|
grep ^ID=arch /etc/os-release
|
|
}
|
|
|
|
function os-release {
|
|
grep ^ID= /etc/os-release | cut -d '=' -f2
|
|
}
|
|
|
|
function askConfirmation {
|
|
case "$1" in
|
|
y | Y | yes | YES)
|
|
QUESTION="(Y/n)?"
|
|
DEFAULT=0
|
|
;;
|
|
*)
|
|
QUESTION="(y/N)?"
|
|
DEFAULT=1
|
|
;;
|
|
esac
|
|
read -rp "$QUESTION : " choice
|
|
case "$choice" in
|
|
y | Y | yes | YES) return 0 ;; #true
|
|
n | no | N | NO) return 1 ;; #false
|
|
*) return $DEFAULT ;;
|
|
esac
|
|
}
|