Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/bash/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Linux 用于检查多个正在运行的进程的Bash脚本_Linux_Bash_Shell - Fatal编程技术网

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

Linux 用于检查多个正在运行的进程的Bash脚本,linux,bash,shell,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循环检

我使用以下代码来确定进程是否正在运行:

#!/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
如果你只是想看看他们中的任何一个是否在运行,那么你不需要厕所。只需将列表交给
grep

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

使用单独的流程列表:

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

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

关于你的问题,如何循环通过一系列进程,你最好使用一个数组。一个有效的例子可能是这样的:

(备注:避免大写变量,这是一种非常糟糕的bash实践):


干杯

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

关于你的问题,如何循环通过一系列进程,你最好使用一个数组。一个有效的例子可能是这样的:

(备注:避免大写变量,这是一种非常糟糕的bash实践):

干杯

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

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