我可以用正则表达式成功使用正则表达式for循环?
$ cat while.sh
#!/bin/sh
arr=(a1c a2c a3c b4c)
i=0
while [[ ${arr[i]} =~ a(.)c ]]
do
echo ${BASH_REMATCH[1]}
((i++))
done
$ ./while.sh
1
2
3
for循环运行while循环会导致此错误
$ cat for.sh
#!/bin/sh
arr=(a1c a2c a3c b4c)
for ((i=0; [[ ${arr[i]} =~ a(.)c ]]; i++))
do
echo ${BASH_REMATCH[1]}
done
$ ./for.sh
./for.sh: line 3: ((: [[ a1c =~ a(.)c ]]: syntax error: operand expected (error
token is "[[ a1c =~ a(.)c ]]")
实际上,该语法对于for循环是有效的:'for((i = 0; i <5; i ++));做echo $ i;完成' – mikebabcock
我知道,因为'我<5'是一个算术表达式。他的正则表达式不是。编辑我的答案,使其更清楚我的意思是,这是不是一个有效的构造,他有,而不是一般。 – Mitzimoto
他需要的是$?来自'[[evaluation]]'的价值,而不是它的结果,但是在他的版本中,只要评估是错误的,循环就会退出。假设他的意思是这样。 – mikebabcock