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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13330848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 03:45:46  来源:igfitidea点击:

Bash script to check multiple running processes

linuxbashshell

提问by Citizen SP

I'm made the following code to determine if a process is running:

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

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

I would like to use my code to check multiple processes and use a list as input (see below), but getting stuck in the foreach loop.

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

CHECK_PROCESS=nginx, mysql, etc

What is the correct way to use a foreach loop to check multiple processes?

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

回答by gniourf_gniourf

If your system has pgrepinstalled, you'd better use it instead of the greping of the output of ps.

如果你的系统已经pgrep安装了,你最好用它代替的grep输出的ING ps

Regarding you're question, how to loop through a list of processes, you'd better use an array. A working example might be something along these lines:

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

(Remark: avoid capitalized variables, this is an awfully bad bash practice):

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

Cheers!

干杯!

回答by dimir

Create file chkproc.sh

创建文件 chkproc.sh

#!/bin/bash

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

And then run:

然后运行:

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

Unless you have some old or "weird" system you should have pgrepavailable.

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

回答by P.P

Use a separated list of of processes:

使用单独的进程列表:

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

If you simply want to see if either one of them is running, then you don't need loo. Just give the list to grep:

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

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