I am attempting to check if an argument is an array with the following code:
if [[ $(declare -p $1) ]] != *-a*;
Here $1 is a string with the value "123". I get the following error message from bash:
`arrays.bash: line 23: declare: 123: not found
This code works if I pass an array as an argument but not a string. I want to verify that the argument is either an array or an associative array. I have no concern with the contents at this point, I only want the type. Any ideas on how to do this?
CodePudding user response:
After all, why worry about the types, if you are relying on it perhaps your approach is wrong or you may need a strong-typed language
% v=1
% declare -p v
declare -- v="1"
% echo $v
1
% echo ${v[@]}
1
% v[1]=2
% declare -p v
declare -a v=([0]="1" [1]="2")
% echo ${v[@]}
1 2
CodePudding user response:
To check if an argument is an array or associative you can do something like this:
if [[ "$(declare -p "${1}")" =~ declare\ \-a ]] ; then
echo "TRUE"
fi
However, in bash variables are untyped. For this reason it would probably be best to use a different langauge in this scenario.