使用布尔和计数器时使用Bash脚本

时间:2014-01-14 11:03:08

标签: bash

有人可以帮我解决这个问题......我似乎无法获得一个有效的声明(它永远不会进入循环)...尝试了许多不同的语法而且我被卡住了。

tries=0
success=false

while (!${success} && ${tries} -lt 10); do
  {
    echo "Trying..." &&
    myCommand &&
    success=true &&
    echo "Success"
  } || {
    success=false &&
    echo "Failed"
  }
  let tries=tries+1
done

2 个答案:

答案 0 :(得分:2)

稍作改动

tries=0
success=false

while (( !${success} && ${tries} < 10 )); do
  {
    echo "Trying..." &&
    myCommand &&
    success=true &&
    echo "Success"
  } || {
    success=false &&
    echo "Failed"
  }
  let tries=tries+1
done

Difference in Bash between IF statements with parenthesis and square brackets

答案 1 :(得分:2)

您似乎正在尝试在bash中编写C代码。具体来说,使用success作为布尔标志和可执行程序有点尴尬。尝试

while (( tries < 10 )); do
    { myCommand && echo Success && break; } || { echo Failed && let tries=tries+1; }
done

使用明确的if语句也会更具可读性:

while (( tries < 10 )); do
    if myCommand; then
        echo Success
        break
    else
        echo Failed
        let tries=tries+1
    fi
done