Bash从解析的字符串动态创建数组

时间:2010-09-28 22:30:24

标签: arrays bash

我正在尝试使用bash中的for循环从已经解析的字符串(参数扩展)动态创建嵌套数组,但我失败了:

user@server:/home/user> foo=one,two,three
user@server:/home/user> for i in ${foo//,/" "}; do echo ${i}; done
one
two
three
user@server:/home/user> for i in ${foo//,/" "}; do declare -a ${i}=(var1=foo var2=foo var3=foo); done
-bash: syntax error near unexpected token `('

我可以手动创建嵌套数组,它可以工作:

user@server:/home/user> declare -a one=(var1=foo var2=foo var3=foo)
user@server:/home/user> echo ${one[*]}
var1=foo var2=foo var3=foo

任何帮助都将不胜感激!

1 个答案:

答案 0 :(得分:1)

ecik@ecikovo / $ x=one
ecik@ecikovo / $ echo $x
one
ecik@ecikovo / $ declare -a $x=(var1=foo var2=foo)
bash: błąd składni przy nieoczekiwanym znaczniku `('
ecik@ecikovo / $ declare -a $x='(var1=foo var2=foo)'
ecik@ecikovo / $ echo ${one[0]}
var1=foo
ecik@ecikovo / $ echo ${one[1]}
var2=foo