bash 4.2 / 4.3:C风格循环中的不同行为

时间:2015-06-10 15:26:35

标签: bash loops version

bash 4.2显示C样式for循环中假定的正确行为:

me@server:/some/dir# TIMES=30; for (( n=0; n<$(shuf -i ${TIMES}-$(expr ${TIMES} + 20) -n 1); n++ )); do echo $n; done
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
me@server:/some/dir# bash --version
GNU bash, Version 4.2.25(1)-release (x86_64-pc-linux-gnu)
(...)
me@server:/some/dir#

bash 4.3下的相同内容会引发错误:

me@server:/some/dir# TIMES=30; for (( n=0; n<$(shuf -i ${TIMES}-$(expr ${TIMES} + 20) -n 1); n++ )); do echo $n; done
-bash: syntax error near unexpected token `newline'
me@server:/some/dir# bash --version
GNU bash, Version 4.3.30(1)-release (x86_64-pc-linux-gnu)
(...)

然而,找到${TIMES}${TIMES}+20之间的随机数的部分有效:

me@server:/some/dir# shuf -i 20-50 -n 1
26
me@server:/some/dir#

所以直接插入数字而不是$() - 替换它:

me@server:/some/dir# TIMES=30; for (( n=0; n<26; n++ )); do echo $n; done
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
me@server:/some/dir#

这里发生了什么?有什么想法为什么子shell在bash 4.3下没有正确执行?

1 个答案:

答案 0 :(得分:5)

如果您将$(expr替换为$((,它就会开始工作:

TIMES=30
for (( n=0; n < $(shuf -i $TIMES-$((TIMES + 20)) -n 1); n++ )) ; do
    echo $n
done