Created
December 12, 2024 05:54
-
-
Save darkseid4nk/ebece6c2bcc61b2aa0a005672e6ff88d to your computer and use it in GitHub Desktop.
Helper functions for variables.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var_empty(){ | |
# var_empty "_varname" | |
# var_empty "_array[index]" | |
# var_empty "_dict[key]" | |
# Returns 0 if a variable is set to an empty string | |
[[ -z ${!1-unset} ]] && return 0 || return 1 | |
} | |
var_gettype(){ | |
# var_gettype "_varname" | |
# Returns the type of variable | |
local var=$( declare -p $1 2>/dev/null) | |
local reg='^declare -n [^=]+=\"([^\"]+)\"$' | |
while [[ $var =~ $reg ]]; do | |
var=$( declare -p ${BASH_REMATCH[1]} ) | |
done | |
case "${var#declare -}" in | |
a*) | |
echo "ARRAY" | |
;; | |
A*) | |
echo "DICT" | |
;; | |
i*) | |
echo "INT" | |
;; | |
x*) | |
echo "EXPORT" | |
;; | |
*) | |
echo "OTHER" | |
;; | |
esac | |
} | |
var_is_array(){ | |
# var_is_array "_arrayname" | |
# Returns 0 if value is an array. Returns 1 otherwise. | |
[[ "$(declare -p -- "$1" 2>/dev/null)" == "declare -a "* ]] && return 0 || return 1 | |
} | |
var_is_dict(){ | |
# var_is_dict "_dictname" | |
# Returns 0 if value is a dictionary. Returns 1 otherwise. | |
[[ "$(declare -p -- "$1" 2>/dev/null)" == "declare -A "* ]] && return 0 || return 1 | |
} | |
var_is_ref(){ | |
# var_is_ref "_refname" | |
# Returns 0 if the variable is a reference. Returns 1 otherwise | |
[[ "$(declare -p -- "$1" 2>/dev/null)" == "declare -n "* ]] && return 0 || return 1 | |
} | |
var_is_unset(){ | |
# var_is_unset "_varname" | |
# var_is_unset "_arr[index]" | |
# var_is_unset "_dict[key]" | |
# Returns 0 if <variable,index,or key> is unset. Returns 1 otherwise. | |
[[ -z "${!1+set}" ]] && return 0 || return 1 | |
} | |
var_is_unset_or_empty(){ | |
# var_is_unset_or_empty "_varname" | |
# var_is_unset_or_empty "_arr[index]" | |
# var_is_unset_or_empty "_dict[key]" | |
# Returns 0 if <variable,index,or key> is unset or empty. Returns 1 otherwise. | |
[[ -z "${!1}" ]] && return 0 || return 1 | |
} | |
var_isset(){ | |
# var_is_unset "_varname" | |
# var_is_unset "_arr[index]" | |
# var_is_unset "_dict[key]" | |
# Returns 0 if <variable> has been declared and has any value other than empty. Returns 1 otherwise. | |
[[ -n ${!1} ]] && return 0 || return 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment