In bash, is it possible to put several arrays inside quotes and then access them?

笑着哭i 提交于 2020-01-15 12:33:32

问题


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,


回答1:


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


来源:https://stackoverflow.com/questions/19919652/in-bash-is-it-possible-to-put-several-arrays-inside-quotes-and-then-access-them

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!