linux - 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
解决方案
本质上,您想要实现逻辑 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
推荐阅读
- google-bigquery - BigQuery ML 如何处理 NULL 数字特征?
- actionscript-3 - removeChild 不删除对象的子项
- javascript - 当我在移动用户分辨率之后更改桌面用户的屏幕分辨率时,导航菜单项不显示内联
- vbscript - 在 VBSCript 错误处理中显示行号
- java - 下拉百里香叶 jpa
- c++ - 使用 execlp() 打印 pstree
- android - Android Studio:模拟器:进程以退出代码 -1073741819 (0xC0000005) 完成
- php - 匹配/提取两个字符串之间的所有字符
- c++ - 未找到 Qt 5.12 D3D 编译器模块
- windows - Wix Toolkit - MSI 安装程序 - 启动已安装的应用程序时,窗口的弹出窗口不断出现