簡體   English   中英

Bash腳本檢查多個正在運行的進程

[英]Bash script to check multiple running processes

我編寫了以下代碼來確定進程是否正在運行:

#!/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循環檢查多個進程的正確方法是什么?

如果您的系統已安裝pgrep ,則最好使用它而不是ps輸出的grep ing。

關於您的問題,如何遍歷進程列表,最好使用數組。 一個可行的示例可能與以下內容類似:

(備注:避免使用大寫字母的變量,這是非常糟糕的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

干杯!

使用單獨的進程列表:

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

創建文件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可用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM