2012-11-11 49 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可用。

相關問題