Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if variable is an array?

Tags:

arrays

bash

I have a loop over variable names and I need to check if content of a variable is an array or not:

for varname in AA BB CC; do   local val   if [ "$varname" is array ]; then # how can I perform this test?     echo do something with an array   else     echo do something with a "'normal'" variable   fi done 

How do I do it?

like image 417
wujek Avatar asked Jan 25 '13 15:01

wujek


People also ask

Can a variable be an array?

An array is a variable containing multiple values. Any variable may be used as an array. There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously.

How do you check if a variable is in an array Python?

To check if an array contains an element or not in Python, use the in operator. The in operator checks whether a specified element is an integral element of a sequence like string, array, list, tuple, etc.


2 Answers

To avoid a call to grep, you could use:

if [[ "$(declare -p variable_name)" =~ "declare -a" ]]; then     echo array else     echo no array fi 
like image 140
Reuben W Avatar answered Sep 22 '22 06:09

Reuben W


According to this wiki page, you can use this command:

declare -p variable-name 2> /dev/null | grep -q '^declare \-a' 
like image 22
Bastien Jansen Avatar answered Sep 19 '22 06:09

Bastien Jansen