Skip to content

Instantly share code, notes, and snippets.

@DavidEGrayson
Created November 12, 2015 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidEGrayson/9eada135070b8d3731e2 to your computer and use it in GitHub Desktop.
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
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