3

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

?

3
  • 2
    When you are at the point of needing arrays in shell, shouldn't you be considering Python instead? Commented Nov 28, 2009 at 20:11
  • It would help if you said which shell you're using. Commented Nov 28, 2009 at 21:10
  • He said he is using sh shell Commented Feb 18, 2016 at 9:00

4 Answers 4

3

Assuming bash

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

for index in ${!array1[*]}
do
    printf "%s %s\n" ${array1[$index]} ${array2[$index]}
done
Sign up to request clarification or add additional context in comments.

1 Comment

in my shell it has to be array1="mazda toyota honda" otherwise I get a syntax error
1

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
$ 

Comments

1

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

Comments

1

You can use the $IFS var to fake arrays for example (works with any posix compilant 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

If you wrap this in a function you can use them like a real array

1 Comment

To improve the quality of your post, please include why/how your answer solves the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.