Home > database >  How to use a variable defined in two nested for loops as stopargument for the thrid loop
How to use a variable defined in two nested for loops as stopargument for the thrid loop

Time:12-14

I have three loops for example that contain the code

for i in $words
do
height=$((20   (10 * i)))
done

for j in {0..3}
do
x=$((10   (15 * j)))
done

for k in $height
do 
y=$((110 - k)/2))
done

With $words containing the numbers

0 3 4 5

height will give

20 
50 
60 
70

x will give

10
25
40
55

and y should give

45
30
25
20

But the problem is that height is defined in one of the for loops so I can't use it as an argument for the last for loop. The table of height is also vertical and not horizontal. When I do a nested for loop I get too many rows.

My desired output should look like this using echo please for example

echo "<$height> <$x> <$y>

and it should look like this

20   1O   40
50   25   30
60   40   25
70   55   20

Thank you

CodePudding user response:

If you don't want to nest loops and every loop will iterate the same number of times, you can use arrays to keep track of their values.

#!/bin/bash
# Create arrays to store each value
h_values=()
x_values=()
y_values=()
words="0 3 4 5"

for i in $words
do
# append an array with a calculated value
h_values =( "$((20   (10 * i)))" )
done

for j in {0..3}
do
x_values =( "$((10   (15 * j)))" )
done

# this loops over each element of h_values, the heights we calculated before
for k in "${h_values[@]}"
do 
y_values =( "$(((110 - k)/2))" )
done

# C-style for loop to print the i-th index of each array in order
for ((i=0 ; i < ${#h_values[@]} ; i  )) ; do
  printf '%s %s %s\n' "${h_values[i]}" "${x_values[i]}" "${y_values[i]}"
done

With your word values I get this output:

20 10 45
50 25 30
60 40 25
70 55 20

Which doesn't quite match your expected output but is pretty close. Maybe the math is a little off somewhere.

  •  Tags:  
  • bash
  • Related