2

Im trying to use nested for loop in shell script to get output like below:

i=1 j=1 iteration 1
i=2 j=2 iteration 2  
i=3 j=1 iteration 3  
i=4 j=2 iteration 4  
i=5 j=1 iteration 5  
i=6 j=2 iteration 6  

Something like

for (( i=1; i <= 6;i++ ))
do
        for ((j=1;j<2;j++))
        do
        echo i=$i;echo j=$j;echo iteration $i
        ...
        done
done
3
  • What's your question? Are you asking how to have j alternate between 1 and 2 depending on whether i is odd or even? Commented Nov 29, 2016 at 2:49
  • this isn't much of a nested loop question. More of an even/odd for "$j" question Commented Nov 29, 2016 at 2:51
  • I want j to alternate between 1 and 2 but it does not depends whether i is odd or even. Commented Nov 29, 2016 at 2:52

2 Answers 2

2

In Bash/Zsh/Ksh93 (at least):

let iter=0

for (( i=1; i <= 6; ))
do
  for (( j=1; j<=2; j++, i++ ))
  do
    printf "i=%d j=%d iteration %d\n" $i $j $(( ++iter ))
  done
done

Output

i=1 j=1 iteration 1
i=2 j=2 iteration 2
i=3 j=1 iteration 3
i=4 j=2 iteration 4
i=5 j=1 iteration 5
i=6 j=2 iteration 6

And the following should work in the standard command language as well:

iter=0
i=0

while (( i <= 6 ))
do
  j=0
  while (( ++j <= 2 && ++i <= 6 ))
  do
    printf "i=%d j=%d iteration %d\n" $i $j $(( ++iter ))
  done
done
Sign up to request clarification or add additional context in comments.

Comments

0
#!/usr/bin/env bash

for i in `seq 1 6`; do
        if [[ $((i%2)) -eq 1 ]]; then
                echo "i=$i j=1 iteration $i"
        else
                echo "i=$i j=2 iteration $i"
        fi

done

Comments

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.