【问题标题】:While loop that exit when the condition is metwhile 循环,当条件满足时退出
【发布时间】:2023-01-12 18:59:04
【问题描述】:

我需要在 bash 脚本中编写一个 while 循环,当进程成功结束时它会退出,到目前为止我已经尝试过的是;

VAR=`ps -ef |grep -i tail* |grep -v grep |wc -l`
while true; do
{
if [ $VAR = 0 ]
then
echo "Sending MAils ...."
exit
fi
}
done

【问题讨论】:

    标签: bash shell unix


    【解决方案1】:

    使用 break 而不是 exit 继续执行脚本。

    另外,不需要{

    【讨论】:

    • 而且,VAR 不会在循环内改变,所以要么是无操作,要么是无限循环。
    • 是的,刚才提到了问题的答案,脚本有多个错误:)
    【解决方案2】:

    您的脚本有很多错误。在寻求人工帮助之前,可能先尝试https://shellcheck.net/

    您需要更新循环内变量的值。

    你似乎在重塑pgrep,很糟糕。

    (正则表达式 tail* 查找 taitailtailltailll ...您实际上希望它做什么?)

    要跳出循环并在外面继续,请使用break

    循环周围的大括号是多余的。这是 shell 脚本,不是 C 或 Perl。

    您可能正在寻找类似的东西

    while true; do
       if ! pgrep tail; then
          echo "Sending mails ...."
          break
       fi
    done
    

    这完全避免了使用变量;如果你确实需要一个变量,don't use upper case for your private variables.

    【讨论】:

      猜你喜欢
      • 2022-01-13
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多