首页 > 解决方案 > Bash 脚本 For Loop 包含 if/else 问题

问题描述

我正在使用 bash 脚本来查看给定的进程是否正在运行。如果它们没有运行,那么它会打印 Process `$p' is not running。但是,如果所有进程都在运行,我希望它只打印一次:“进程正在运行”。

但问题是它多次打印出“进程正在运行”,即使有进程没有运行,它也会被打印出来。我认为 For 循环有问题。

#!/bin/bash


check_process=( "ssh" "mysql" "python" )

for p in "${check_process[@]}"; do
    if ! pgrep -x  "$p" > /dev/null; then
        echo "Process \`$p' is not running"
    else
        echo "Processes are running"
    fi
done

标签: linuxbash

解决方案


本质上,您想要实现逻辑 AND 条件。你可以这样做:

#!/bin/bash


check_process=( "ssh" "mysql" "python" )

allrunning=1
for p in "${check_process[@]}"; do
    if ! pgrep -x  "$p" > /dev/null; then
        echo "Process \`$p' is not running"
        allrunning=0
    fi
done
if [ $allrunning -eq 1 ]
then
      echo "Processes are running"
fi

推荐阅读