2010-09-29 109 views
1

下面的if [ {$i[0]} = "true" ]失败。我似乎无法弄清楚如何在if语句中获得{$i[0]}的正确格式。Bash for循环if语句数组名称引用为变量

#!/bin/bash 
foo=bar1,bar2 

for i in ${foo//,/" "} 
do 
declare -a ${i}='(true null null null)' 
done 

for i in ${foo//,/" "} 
do 
if [ {$i[0]} = "true" ] 
then echo "yes" 
eval "echo \${$i[*]}" 
else echo "no" 
fi 
done 

我有一个有点相关的问题,有人还跟帮我 Bash echo all array members when array is referenced as a variable in a loop

感谢您的帮助!

回答

2

你也必须在这里使用eval,但我会再次推荐一个不同的整体设计。

if [ "$(eval "echo \${$i[0]}")" = "true" ] 

编辑:

提案的重新设计(使用从点点推假想场景我见过的你在做什么):

#!/bin/bash 
# sample input: $1=foo,bar,baz 
saveIFS=$IFS 
IFS=','  # word splitting will be done using a comma as the delimiter 
names=($1) # store the names for cross reference or indirection 
IFS=$saveIFS 

# Constants: 
declare -r heater=0 
declare -r exhaust=1 
declare -r light=2 
declare -r rotation=3 

# deserialize and serialize: 

# initialize settings 
for ((i=0; i<${#names}; i++)) 
do 
    declare ${names[i]}=$i # setup indirection pointers 
    config[i]="null null null null" 
done 

# by index: 
vals=(${config[0]})  # deserialize 
echo ${vals[light]}  # output value 
vals[light]="false"  # change it 
config[0]=${vals[@]}  # reserialize 

# by name: 
vals=(${config[$foo]}) 
echo ${vals[light]}  # output value 

# by indirection: 
vals=(${config[${!names[0]}]}) 
echo ${vals[light]}  # output value 

# iteration using indirection 
for name in ${names[@]} 
do 
    echo "Configuration: $name" 
    echo " all settings: ${config[${!name}]}" 
    vals=(${config[${!name}]}) 
    for setting in heater light # skipping exhaust and rotation 
    do 
     echo " $setting: ${vals[${!setting}]}" 
    done 
done 

这可能给你可以利用一些想法和原则。如果你使用Bash 4,你可以使用关联数组,这将大大简化这种类型的事情。你也可以使用函数来做一些简化。

+0

工作表示感谢。作为一种不同的设计,你有什么想法?洗耳恭听。我知道你谈到了使用字符串而不是数组。你想做'bar1 = true,null,null,null'而不是像'$ {foo //,/“”}'那样使用“Shell Parameter Expansion”来读取,写入和修改我存储的参数? – spaghettiwestern 2010-09-30 15:27:37

+0

@spaghettiwestern:看到我的编辑的一些想法。如果出于安全原因,最好避免使用“eval”(http://mywiki.wooledge.org/BashFAQ/048)。 – 2010-09-30 16:42:08

+0

丹尼斯再次感谢你的帮助。我会查看你的建议。 – spaghettiwestern 2010-09-30 19:42:38