Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to check if an a variable is defined as an array in Bash
foo=" hi declare -a foo"
bar=(a b)
lint_var_defined_as_non_array() {
if [[ "${!1+x}" == "" ]]; then
return 1 # not defined
fi
if [[ "$(declare -p $1)" == "declare -a "* ]]; then
return 1 # defined as an array
fi
return 0
}
lint_var_defined_as_array() {
if [[ "${!1+x}" == "" ]]; then
return 1 # not defined
fi
if [[ "$(declare -p $1)" == "declare -a "* ]]; then
return 0 # defined as an array
fi
return 1
}
if lint_var_defined_as_non_array foo; then
echo foo is non array
fi
if lint_var_defined_as_non_array bar; then
echo bar is non array
fi
if lint_var_defined_as_non_array car; then
echo car is non array
fi
if lint_var_defined_as_array foo; then
echo foo is array
fi
if lint_var_defined_as_array bar; then
echo bar is array
fi
if lint_var_defined_as_array car; then
echo car is array
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.