LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash array - more than one value per item? (https://www.linuxquestions.org/questions/programming-9/bash-array-more-than-one-value-per-item-847018/)

jsteel 11-28-2010 06:16 AM

Bash array - more than one value per item?
 
Hi,

Hopefully something simple but can't seem to find an answer. Is it possible to have an array in Bash that can hold more than one value per item?

For example I would like an array like this:

Entry 1: apple, green
Entry 2: banana, yellow

And be able to call the fruit names and their colour in a list. Something like:

for fruit in "${array[@]}"
do
echo a $fruit is $colour
done

If that is possible, is there a limit to values per item? For example some entries in an array could be:

Entry 1: apple, green, round, pips, tree
Entry 2: banana, yellow, long, skin, tree

And I would like to pick out the values such as #3 being "round" and "long".

Thanks

catkin 11-28-2010 06:31 AM

The classic solution when a language supports only 1 dimensional arrays is an array for each attribute, following your example a name array, a colour array ... then you can loop through:
Code:

for ((i=0; i<${names[*]}; i++))
do
  echo a ${names[i]} is ${colours[i]}
done

This can be extended using content addressable arrays so that, for example, the value of colours[apple] is green.

Alternatively you can have a single array with lists of attributes such as the "apple, green, round, pips, tree" in your example. To access an individual attribute you need to parse the list; important that the list separator character cannot appear in the data.

grail 11-28-2010 06:55 AM

Another possibility to could depend on how well you know the data. If you know ahead of time how many elements to each array entry and what they refer to you could do something like:
Code:

array=( "apple,green,round,pips,tree" "banana,yellow,long,skin,tree" )

for entry in ${array[*]}
do
    set - $(echo "$entry" | tr ',' ' ')

    echo "name = $1"
    echo "colour = $2"
    echo "to grow = $3"
    echo "grows on = $4"
done


jsteel 11-30-2010 02:28 PM

Thanks for the replies; both great!


All times are GMT -5. The time now is 12:25 PM.