【问题标题】:Bash - While loop doesn't stopBash - While 循环不会停止
【发布时间】:2021-08-18 01:19:02
【问题描述】:

我编写了一个脚本,其中有一个 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 ]];

【问题讨论】:

  • foo=(( 无效。你没有收到语法错误吗? it returns an integer 函数 return 是整数还是打印整数?您的代码检查是否打印整数。
  • @KamilCuk 打字错误对不起。忘记加$
  • @KamilCuk 它打印一个整数
  • 你在问XY问题吗?
  • @KamilCuk 是的,这是一个 XY 问题。

标签: bash while-loop


【解决方案1】:

我的实际问题是这些条件之间有什么区别?

while [ "$(finder $foo)" = "0" ];
# versus
while [[ $(finder $foo) -eq 0 ]];

总结一下:

[ "$(finder $foo)" = "0" ]; [[ $(finder $foo) -eq 0 ]]
portable and POSIX compatible bash specific
calls a [ or test command calls a bash (very) special builtin [[
compares the strings as they are does arithmetic expansion before comparing
does string comparison does arithmetic comparison
uses quoting " to disable
word splitting and filename expansion
special semantics of [[ disable
word splitting and filename expansion

【讨论】:

  • 那么在排序中,我可以将[[ $(finder $foo) -eq 0 ]] 用于我当前的目的吗?我做错了什么?
  • 是的。不知道 - 提交minimal reproducible example。请参阅How to Ask
猜你喜欢
  • 2013-03-12
  • 2019-07-29
  • 2015-12-30
  • 2015-08-06
  • 1970-01-01
  • 2020-03-23
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
相关资源
最近更新 更多