Bash脚本用于检查多个正在运行的进程

时间:2012-11-11 11:52:50

标签: linux bash shell

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

#!/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循环检查多个进程的正确方法是什么?

3 个答案:

答案 0 :(得分:3)

如果您的系统安装了pgrep,则最好使用它而不是grep输出的ps

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

(注:避免大写变量,这是一个非常糟糕的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

干杯!

答案 1 :(得分:1)

使用单独的进程列表:

#!/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

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

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

答案 2 :(得分:1)

创建文件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

相关问题