【问题标题】:Bash script to check multiple running processes用于检查多个正在运行的进程的 Bash 脚本
【发布时间】:2012-11-11 11:52:50
【问题描述】:

我编写了以下代码来确定进程是否正在运行:

#!/bin/bash
ps cax | grep 'Nginx' > /dev/null
if [ $? -eq 0 ]; then
  echo "Process is running."
else
  echo "Process is not running."
fi

我想使用我的代码检查多个进程并使用列表作为输入(见下文),但卡在 foreach 循环中。

CHECK_PROCESS=nginx, mysql, etc

使用 foreach 循环检查多个进程的正确方法是什么?

【问题讨论】:

    标签: linux bash shell


    【解决方案1】:

    如果你的系统已经安装了pgrep,你最好使用它而不是ps输出的greping。

    关于您的问题,如何循环遍历进程列表,您最好使用数组。一个可行的例子可能是这样的:

    (备注:避免大写变量,这是一个非常糟糕的 bash 做法):

    #!/bin/bash
    
    # Define an array of processes to be checked.
    # If properly quoted, these may contain spaces
    check_process=( "nginx" "mysql" "etc" )
    
    for p in "${check_process[@]}"; do
        if pgrep "$p" > /dev/null; then
            echo "Process \`$p' is running"
        else
            echo "Process \`$p' is not running"
        fi
    done
    

    干杯!

    【讨论】:

      【解决方案2】:

      使用单独的进程列表:

      #!/bin/bash
      PROC="nginx mysql ..."
      for p in $PROC
      do
        ps cax | grep $p > /dev/null
      
        if [ $? -eq 0 ]; then
          echo "Process $p is running."
        else
          echo "Process $p is not running."
        fi
      
      done
      

      如果您只是想查看其中任何一个是否正在运行,那么您不需要 loo。只需将列表提供给grep

      ps cax | grep -E "Nginx|mysql|etc" > /dev/null
      

      【讨论】:

        【解决方案3】:

        创建文件 chkproc.sh

        #!/bin/bash
        
        for name in $@; do
            echo -n "$name: "
            pgrep $name > /dev/null && echo "running" || echo "not running"
        done
        

        然后运行:

        $ ./chkproc.sh nginx mysql etc
        nginx: not running
        mysql: running
        etc: not running
        

        除非你有一些旧的或“奇怪”的系统,否则你应该有 pgrep 可用。

        【讨论】:

          猜你喜欢
          • 2011-02-23
          • 1970-01-01
          • 2014-08-21
          • 1970-01-01
          • 1970-01-01
          • 2020-11-04
          • 1970-01-01
          • 2018-11-26
          • 2020-05-06
          相关资源
          最近更新 更多