views:

88

answers:

3

Hi,

I use code in !/bin/sh like this:

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

for m in $LIST1
do
 echo $m
done

As you can see this currently prints out only the make of the car. How can I include the year to each "echo" based on the same positions so that I get results like:

mazda 2009

toyota 2006

honda 2010

?

+1  A: 

Assuming bash

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

for index in ${!array1[*]}
do
    printf "%s %s\n" ${array1[$index]} ${array2[$index]}
done
Nifle
in my shell it has to be array1="mazda toyota honda" otherwise I get a syntax error
goe
and what shell is that?
glenn jackman
+1  A: 

Well, bash does have arrays, see man bash. The generic posix shell does not.

The shell is not precisely a macro processor, however, and so any metaprogramming must be processed by an eval or, in bash, with the ${!variable} syntax. That is, in a macro processor like nroff you can easily fake up arrays by making variables called a1, a2, a3, a4, etc.

You can do that in the posix shell but requires a lot of eval's or the equivalent like $(($a)).

$ i=1 j=2; eval a$i=12 a$j=34
$ for i in 1 2; do echo $((a$i)); done
12
34
$

And for a bash-specific example...

$ a=(56 78)
$ echo ${a[0]}
56
$ echo ${a[1]}
78
$
DigitalRoss
+1  A: 

You can use arrays but just to be different here's a method that doesn't need them:

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

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