Created
November 12, 2015 08:26
-
-
Save DavidEGrayson/9eada135070b8d3731e2 to your computer and use it in GitHub Desktop.
How to check if an a variable is defined as an array in Bash
This file contains 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
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