以下if [ {$i[0]} = "true" ]
失败。我似乎无法弄清楚如何在if语句中获得{$i[0]}
的正确格式。
#!/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
感谢您的帮助!
答案 0 :(得分: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,你可以使用关联数组,这将大大简化这种类型的事情。您还可以使用函数进行一些简化。