我写了一个脚本,其中有一个 while 循环。我尝试了两种外观相似的条件,但出于某种奇怪的原因,其中一个条件有效,而另一个无效。
有效,循环按预期停止。
function finder {
# it prints an integer
}
for ((current = 1; current <= $total_lines; current++)); do
foo=$(( current - 1 ))
while [ "$(finder $foo)" = "0" ]; do
(( foo-- ))
done
done
不起作用,while 循环永远不会停止。
function finder {
# it prints an integer
}
for ((current = 1; current <= $total_lines; current++)); do
foo=$(( current - 1 ))
while [[ $(finder $foo) -eq 0 ]]; do
(( foo-- ))
done
done
我的实际问题是这些条件之间有什么区别?我希望第二个条件以某种方式起作用。
while [ "$(finder $foo)" = "0" ];
# versus
while [[ $(finder $foo) -eq 0 ]];
答案 0 :(得分:1)
我的实际问题是这些条件之间有什么区别?
while [ "$(finder $foo)" = "0" ];
# versus
while [[ $(finder $foo) -eq 0 ]];
总结:
[ "$(finder $foo)" = "0" ]; |
[[ $(finder $foo) -eq 0 ]] |
---|---|
便携且兼容 POSIX | bash 特定 |
调用 [ 或 test 命令 |
调用 bash(非常)特殊的内置 [[ |
按原样比较字符串 | 在比较之前进行算术扩展 |
进行字符串比较 | 进行算术比较 |
使用引用 " 来禁用分词和文件名扩展 |
[[ 的特殊语义禁用分词和文件名扩展 |