Question

I know I can do this:

set=("1 2 3" "4 5 6")
for subset in "${set[@]}"
do
for element in $subset
do
echo $element
done
done

1 2 3 4 5 6 will be printed sequentially. However, I can not do this:

  set="(1 2 3) (4 5 6)"
  for subset in $set
  do
  echo ${subset[2]}
  done

I want to print 3 6. The reason why I want to do this is that I want to have access to whichever element I want to access during iteration instead of iterating one by one. That's why I try to put arrays inside quotes instead of putting quotes inside a big array. Is there any way to do this? Thanks,

Was it helpful?

Solution

Unfortunately, I don't think bash supports multi-dimentional arrays, which sounds like what you're looking for. You can simulate it with a little help from bash itself like so:

x=()
x+=("1,2,3")
x+=("4,5,6")

for val in ${x[@]}; do
    subset=($(echo $val | tr ',' ' '))
    echo ${subset[2]}
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top