How to use arrays in unix shell?

I use the code in! / bin / sh as follows:

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

for m in $LIST1
do
 echo $m
done

As you can see, only the car brand is currently being issued. How can I include a year in each echo based on the same positions to get results such as:

mazda 2009

toyota 2006

honda 2010

?

+3
source share
4 answers

Well, bash has arrays, see man bash. The general posix shell does not work.

, eval , bash, ${!variable}. , , nroff, , , a1, a2, a3, a4 ..

posix, 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
$ 
+1

bash

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

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

, , , , :

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

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

$IFS var , ( posix):

    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

,

+1

Source: https://habr.com/ru/post/1724189/


All Articles