1

I am trying to implement a nested for loop in bash where the inner loop uses the current value of the outer loop in its range but I am getting this error "/drawgraph.sh: line 19: {0..1}: syntax error: operand expected (error token is "{0..1}")"

Here is my code:

for i in {0..499}
do
  for j in {0..$i}
  do
    # other code
  done
done

Here's a java analogy for what I'm trying to do:

for (int i = 0; i < 499; i++) {
  for (int j = 0; j < i; j++) {
    // some code
  }
}
  • 1
    Brace expansion happens before parameter expansion, and `{0..$i}` is not a valid brace expression. – chepner Mar 12 '19 at 22:01

2 Answers2

2

You can just use ((i=0;i<499;i++)) instead of {0..499}:

#!/bin/bash

for ((i=0;i<499;i++))
do
  for ((j=0;j<i;j++))
  do
    echo "$i $j"
  done
done

If you want to use the array syntax you should use $(seq 0 $i) instead of {0..$i}:

#!/bin/bash

for i in {0..499}
do
  for j in $(seq 0 $i)
  do
    echo "$i $j"
  done
done
Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
1

I am afraid that your current approach does not work.

Does anything prevent you from using normal C-style loops?

for ((i = 0; i < 499; i++)); 
do
  for ((j = 0; j < i; j++)); 
  do
    # use $i and $j as you like
  done
done

Adding some evidence here, since it is not the first time this question has been asked. As the answer states, "brace expansion occurs before variables are expanded".

Glains
  • 2,773
  • 3
  • 16
  • 30