user3378320
user3378320

Reputation: 47

how to print results for nested for loops once

I am trying to print results for nested for loop once but I am getting results for various combinations in loop.

Here is my code

for run in 1 2
do 
    for value in 3000 5000 1000
    do
       for percent in 30 40 50
       do
           echo "${percent}percent of ${value}"
       done
    done
 done

I get following output:

for run1:30percent of 3000
for run1:40percent of 3000
for run1:50percent of 3000
for run1:30percent of 5000
for run1:40percent of 5000
for run1:50percent of 5000
for run1:30percent of 1000
for run1:40percent of 1000
for run1:50percent of 1000
for run2:30percent of 3000
for run2:40percent of 3000
for run2:50percent of 3000
for run2:30percent of 5000
for run2:40percent of 5000
for run2:50percent of 5000
for run2:30percent of 1000
for run2:40percent of 1000
for run2:50percent of 1000

I want to print output as

for run1:30percent of 3000
for run1:40percent of 5000
for run1:50percent of 1000
for run2:30percent of 3000
for run2:40percent of 5000
for run2:50percent of 1000

Upvotes: 0

Views: 72

Answers (4)

Aleks-Daniel Jakimenko-A.
Aleks-Daniel Jakimenko-A.

Reputation: 10653

Well, since you didn't specify what you are actually doing:

for run in 1 2; do
    for i in {1..3}; do
        echo "for run$run: $(( (i + 2) * 10 ))percent of $((i * 2000 % 6000 + 1000))"
    done
done

Teehee.

Upvotes: 0

konsolebox
konsolebox

Reputation: 75478

for run in 1 2; do
    for pair in 30:3000 40:4000 50:1000; do
        IFS=: read percent value <<< "$pair"
        echo "for run${run}:${percent}percent of ${value}"
    done
done

Output:

for run1:30percent of 3000
for run1:40percent of 4000
for run1:50percent of 1000
for run2:30percent of 3000
for run2:40percent of 4000
for run2:50percent of 1000

Upvotes: 1

Etan Reisner
Etan Reisner

Reputation: 80931

That's not how loops work.

You probably want to use two arrays and a loop from 0 to ${#array} and then use the loop control variable to index the correct entry in each parallel loop.

values=(3000 5000 1000)
percents=(30 40 50)
for ((i=0; i<=${#values}; i++)); do
    echo "${percents[$i]}percent of ${value[$i]}"
done

Upvotes: 2

user3694166
user3694166

Reputation: 1

u do not need the third for loop. just store the data of third loop in an array and print directly after the second for loop

Upvotes: 0

Related Questions