Question

It sounds simple but I can't do it in a simple way. In shell for loop, two vars

A=" 1 2 3 4"

B=" a b c d"

, try to print 1a 2b 3c 4d. Tried

A=" 1 2 3 4" 
B=" a b c d" 

for m in $A for n in $B; do echo $m$n done.

The output is

1
2
3
4
5

for

l
in
a
b
c
d
e

Anyone can help this out?

Was it helpful?

Solution

Here's one way to do it:

$ A=(1 2 3 4); B=(a b c d); for i in $(seq 0 3); do echo ${A[$i]}${B[$i]}; done
1a
2b
3c
4d

OTHER TIPS

In your attempt, the for cases aren't closed with a ;, so it keeps interpreting words in your second for statement as cases for the first for statement.

Use instead:

A="1 2 3 4" 
B="a b c d" 
for m in $A ; do
    for n in $B ; do 
       echo $m$n
    done
done
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top