linux for循环传参问题

$N=5;for i in {1..$N};do echo $i;done
{1..5}
$N=5;for((i=1;i<$N;i++));do echo $i;done
1
2
3
4
for循环最大值传参,为什么上面的返回结果不是1 2 3 4 5?

你想要变量赋值的话,最好是采用你第二种写法是OK的,还有一种写法也行(但是不推荐):

N=5;for i in $(seq 1 1 $N);do echo $i;done

你的第一种写法是拼接字符串了,而非seq

1 个赞

其实原因写在bash的man手册中:

  • Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretationto the context of the expansion or the text between the braces.

大概就是说,bash会最先读取大括号表达式,在读取的时候表达式内的变量等都会被按照字符进行解析,之后才会进行变量的替换等操作,所以大括号之间的文本不应用任何语法解释。

1 个赞