2012-11-11 143 views
0

如果一个进程正在运行,我作了如下的代码来判断:bash脚本检查多个正在运行的进程

#!/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循环检查多个进程的正确方法?如果你只是想看看是否有任何一个正在运行,那么就不需要厕所

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

回答

1

使用的过程中一个分隔的列表。只要给列表中grep

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

如果你的系统已经安装了pgrep,你最好用它代替grep ING的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

创建文件chkproc.sh

#!/bin/bash 

for name in [email protected]; 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 

除非你有一些旧的或 “怪异” 的系统,你应该有p纤ep可用。

相关问题