首页 > 解决方案 > Dependent Nested For Loops in Bash

问题描述

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
  }
}

标签: javabashshell

解决方案


您可以只使用((i=0;i<499;i++))而不是{0..499}

#!/bin/bash

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

如果你想使用数组语法,你应该使用$(seq 0 $i)而不是{0..$i}

#!/bin/bash

for i in {0..499}
do
  for j in $(seq 0 $i)
  do
    echo "$i $j"
  done
done

推荐阅读