How can I use arrays in unix shell? How can I use arrays in unix shell? unix unix

How can I use arrays in unix shell?


Assuming bash

array1=(mazda toyota honda)array2=(2009 2006 2010)for index in ${!array1[*]}do    printf "%s %s\n" ${array1[$index]} ${array2[$index]}done


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)); done1234$ 

And for a bash-specific example...

$ a=(56 78)$ echo ${a[0]}56$ echo ${a[1]}78$ 


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')