如何在unix shell中使用数组?

时间:2009-11-28 20:09:42

标签: shell loops unix

我在!/ bin / sh中使用代码如下:

LIST1="mazda toyota honda"
LIST2="2009 2006 2010"

for m in $LIST1
do
 echo $m
done

正如您所看到的,目前仅打印出汽车的品牌。 如何根据相同的位置将年份包括在每个“回声”中,以便得到如下结果:

mazda 2009

toyota 2006

honda 2010

4 个答案:

答案 0 :(得分:3)

假设bash

array1=(mazda toyota honda)
array2=(2009 2006 2010)

for index in ${!array1[*]}
do
    printf "%s %s\n" ${array1[$index]} ${array2[$index]}
done

答案 1 :(得分:1)

好吧,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
$ 

答案 2 :(得分:1)

你可以使用数组,但只是不同,这是一个不需要它们的方法:

LIST1="mazda toyota honda"
LIST2="2009 2006 2010"

paste -d' ' <(echo $LIST1 | tr ' ' '\n') <(echo $LIST2 | tr ' ' '\n')

答案 3 :(得分:1)

例如,您可以使用$ IFS var伪造数组(适用于任何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

如果将它包装在一个函数中,你可以像真正的数组一样使用它们