我在!/bin/sh中使用如下代码:
LIST1="mazda toyota honda"
LIST2="2009 2006 2010"
for m in $LIST1
do
echo $m
done
你可以看到,当前只打印出汽车的品牌。如何基于相同的位置为每个“echo”包含年份,以便我可以获得类似以下结果的结果:
mazda 2009
toyota 2006
honda 2010
?
我在!/bin/sh中使用如下代码:
LIST1="mazda toyota honda"
LIST2="2009 2006 2010"
for m in $LIST1
do
echo $m
done
你可以看到,当前只打印出汽车的品牌。如何基于相同的位置为每个“echo”包含年份,以便我可以获得类似以下结果的结果:
mazda 2009
toyota 2006
honda 2010
?
array1=(mazda toyota honda)
array2=(2009 2006 2010)
for index in ${!array1[*]}
do
printf "%s %s\n" ${array1[$index]} ${array2[$index]}
done
嗯,bash确实有数组,请参见man bash
。通用的posix shell没有。
Shell不是一个精确的宏处理器,因此任何元编程都必须通过eval
或在bash中使用${!variable}
语法来处理。也就是说,在像nroff这样的宏处理器中,您可以通过创建名为a1、a2、a3、a4等变量来轻松伪造数组。
您可以在posix shell中执行此操作,但需要大量的eval或等效操作,如$(($a))
。
$ i=1 j=2; eval a$i=12 a$j=34
$ for i in 1 2; do echo $((a$i)); done
12
34
$
而对于一个特定于Bash的示例...
$ a=(56 78)
$ echo ${a[0]}
56
$ echo ${a[1]}
78
$
你可以使用数组,但为了与众不同,这里提供一种不需要它们的方法:
LIST1="mazda toyota honda"
LIST2="2009 2006 2010"
paste -d' ' <(echo $LIST1 | tr ' ' '\n') <(echo $LIST2 | tr ' ' '\n')
您可以使用$IFS变量来模拟数组,例如(适用于任何符合posix标准的shell):
hosts=mingw:bsd:linux:osx # for example you have the variable with all aviable hosts
# the advantage between other methods is that you have still one element and all contens get adressed through this
old_ifs=$IFS #save the old $IFS
IFS=: # say sh to seperate all commands by :
for var in $hosts ; do
# now we can use every element of $var
IFS=$old_ifs
echo $var
done
IFS=$Old_ifs