Bash 脚本中断 "break [n]" 的嵌套循环失败

Bash script break nested loop with "break [n]" failed

这是我的代码:

while [[ "$counter" -gt 0 ]];
do
  startNewTest
  echo -e "\n" | ./myscript.sh send

  while :
  do
    sleep 30
    echo -e "\n Reading status... \n"
    ./myscript.sh status | \
    while read i
    do
      if echo $i | grep -q "$KEYWORD"
      then
        echo -e "\n Starting a new round of test... \n"
        break 2
      fi
    done
  done
  let counter=counter-1
done

当满足if条件时,"break 2"行应该会打破2层循环,对吧?但是,当我 运行 脚本时,它只会打破最内层的循环,并卡在无限 "while :" 循环中。我哪里弄错了? 我也试过"break 3",也没用。

你能用你的 myscript.sh 测试一下吗? 看来您在管道符号之后中断了子流程。 在没有子进程的情况下在 while 循环中获取输出可能会有所帮助:

while [[ "$counter" -gt 0 ]];
do
  startNewTest
  echo -e "\n" | ./myscript.sh send

  while :
  do
    sleep 30
    echo -e "\n Reading status... \n"

    while read i
    do
      if echo $i | grep -q "$KEYWORD"
      then
        echo -e "\n Starting a new round of test... \n"
        break 2
      fi
    done < <(./myscript.sh status)

  done
  let counter=counter-1
done