0

I am trying to pass some values contained in two lists to a simple echo within two nested for loops (the echo is used to look at what is generated inside the inner loop). But the results are not expected. I sure could use some guidance!

Using the bash shell. Here is the snippet:


a_list="0.05 0.10"
b_list="120.0 130.0"
c=44
x=555.0
for a in $a_list
do
   for b in $b_list
       do
           echo $x $a $b $c
       done
done

I expect this:

555.0 0.05 120.0 44
555.0 0.05 130.0 44
555.0 0.10 120.0 44
555.0 0.10 130.0 44

but I get this:

555.0 0.05 120.0 44
 44.0 0.05 130.0
555.0 0.10 120.0 44
 44.0 0.10 130.0

The 2nd and 4th lines are wrong. The 44 appears to echo first and overwrite the 555.0 . If I load the values of the lists directly into the for loop, it works OK. Like this:


c=44
x=555.0
for a in 0.05 0.10
do
   for b in 120.0 130.0
       do
           echo $x $a $b $c
       done
done

Thanks for any help and insights!

2
  • The code you posted seems fine and works for me with the expected result.
    – Janis
    Feb 27, 2015 at 21:16
  • You messed up something, you cannot get 44.0 from 44 in bash in simple way.
    – jimmij
    Feb 27, 2015 at 21:19

1 Answer 1

0

While your code should already work, as noted, you may want to try out using shell arrays...

a_list=(0.05 0.10)
b_list=(120.0 130.0)
c=44
x=555.0
for a in "${a_list[@]}"
do
   for b in "${b_list[@]}"
       do
           echo "$x $a $b $c"
       done
done
4
  • Hi jimmi, when I type your code in I get these two lines: first line=44.0 0.05 (120.0 130.0) 2nd line=44.0 0.10 (120.0 130.0) Weird...
    – atlas50
    Feb 27, 2015 at 21:30
  • Hey jimmi, ignore that. I opened the file in a different text editor and there was an empty line before c=44 I fixed that and it worked as you described. Thanks!!
    – atlas50
    Feb 27, 2015 at 21:37
  • jimmij, why did you change my posted code? Your changes were unnecessary for the question; see shell docs.
    – Janis
    Feb 27, 2015 at 21:37
  • Thank you jimmi and Janis. My problem was a hidden empty line that was not shown in one text editor but revealed in another. Bizzare.. The fact that the code worked for you as-is was the clue.
    – atlas50
    Feb 27, 2015 at 21:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .