bash bash中的while循环使用pgrep来检查服务是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38666191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:57:17  来源:igfitidea点击:

while loop in bash that uses pgrep to check if service exists

bashservicecommand

提问by ewcz

Can someone explain to me why this doesn't work?

有人可以向我解释为什么这不起作用吗?

  /usr/bin/mysqld_safe
  STATUS=$(/usr/bin/pgrep mysql | wc -l)
  while $STATUS -eq 0; do
    echo "$STATUS"
    sleep 1
  done

It defies any logic. Yes I'm not versed in bash :)

它无视任何逻辑。是的,我不精通 bash :)

p.s. I'm trying to wait till service is up, but after running this even echo "$STATUS" is not printed! so loop is not running

ps 我正在尝试等到服务启动,但是在运行此命令后,甚至没有打印 echo "$STATUS" !所以循环没有运行

回答by John1024

This runs mysqld_safe:

这运行mysqld_safe

  /usr/bin/mysqld_safe

This runs pgrepand stores the result in STATUS:

这将运行pgrep并将结果存储在 STATUS 中:

  STATUS=$(/usr/bin/pgrep mysql | wc -l)

STATUS is never updated again. This loops using a constant fixed value of STATUS:

STATUS 永远不会再次更新。此循环使用 STATUS 的恒定固定值:

  while $STATUS -eq 0; do
    echo "$STATUS"
    sleep 1
  done

Note that the test in the while loop is malformed. It should read:

请注意,while 循环中的测试格式错误。它应该是:

  while [ "$STATUS" -eq 0 ]; do

To get live updates, pgrepshould be run within the loop. Further, because pgrepsets an exit code, the test command, [...], is superfluous:

要获得实时更新,pgrep应在循环内运行。此外,因为pgrep设置了退出代码,所以测试命令[...], 是多余的:

To keep the loop running while there are no instances of mysql:

要在没有 mysql 实例时保持循环运行:

while ! /usr/bin/pgrep mysql >/dev/null; do

pgrepreturns success (exit code=0) when it finds a matching process. Since you seem to want the loop to repeat when there is no matching process, we invert the exit code using !.

pgrep找到匹配的进程时返回成功(退出代码=0)。由于您似乎希望在没有匹配进程时重复循环,因此我们使用!.

Or, putting it all back together:

或者,将它们全部重新组合在一起:

/usr/bin/mysqld_safe
while ! /usr/bin/pgrep mysql >/dev/null; do
    echo "No such process"
    sleep 1
done

Assuming that mysqld_safesuccessfully starts, the whileloop will never run. You should only see output from the while loop is mysqld_safefails to start.

假设mysqld_safe成功启动,while循环将永远不会运行。您应该只看到 while 循环的输出mysqld_safe无法启动。

If you instead want a continuous status update:

如果您想要持续的状态更新:

/usr/bin/mysqld_safe
while true; do
    /usr/bin/pgrep mysql >/dev/null
    echo "Current status: $?"
    sleep 1
done

回答by ewcz

perhaps a solution could be something like this

也许解决方案可能是这样的

STATUS=0
while [ $STATUS -eq 0 ]; do
    echo $STATUS
    sleep 1
    STATUS=$(/usr/bin/pgrep mysql | wc -l)
done

one needs to update the STATUSvariable within the loop to reflect the current status.

需要更新STATUS循环内的变量以反映当前状态。