我为Nagios编写了这个脚本,以检查服务是否正在运行。 但是我需要它来比较2个字符串。 完整的脚本如下。
elif [[ $PROCESS_RUNNING1 = "active" && $PROCESS_RUNNING2 = "(running)" || "(exited)" ]]; then
如果我通过shellcheck运行它,那说它是错误的,因为||
。
但是我如何比较2个字符串,这真的是最有效的吗?这可以缩短吗?
elif [[ $PROCESS_RUNNING1 = "active" && $PROCESS_RUNNING2 = "(running)" || $PROCESS_RUNNING2 = "(exited)" ]]; then
非常欢迎所有其他提示,我还是初学者!
#!/bin/bash
while true
do
case $1 in
-s|--service)
DAEMON=$2
shift; shift
;;
-*)
echo "Unknown option: $1"
echo "Usage: -s or --service <daemon name>"
exit 1
;;
*)
break
;;
esac
done
PROCESS_STATUS=$(systemctl status "$DAEMON" | awk 'FNR==3')
PROCESS_RUNNING1=$(systemctl status "$DAEMON" | awk 'FNR==3' | awk '{print $2}')
PROCESS_RUNNING2=$(systemctl status "$DAEMON" | awk 'FNR==3' | awk '{print $3}')
if [[ $(pgrep -f "$DAEMON" | wc -l) -eq 0 ]]; then
echo "$DAEMON PID not found"
exit 1
elif [[ $PROCESS_RUNNING1 != "active" ]]; then
echo "$PROCESS_STATUS"
echo "is not active"
exit 2
elif [[ $PROCESS_RUNNING2 != "(running)" || "(exited)" ]]; then
echo "$PROCESS_STATUS"
echo "is not running or exited"
exit 2
elif [[ $PROCESS_RUNNING1 = "active" && $PROCESS_RUNNING2 = "(running)" || "(exited)" ]]; then
echo "$PROCESS_STATUS"
exit 0
else echo "$DAEMON status unknown, please check"
exit 3
fi
答案 0 :(得分:1)
要打击
$PROCESS_RUNNING2 = "(running)" || "(exited)"
与
大致相同"(exited)" || $PROCESS_RUNNING2 = "(running)"
无论如何,评估为 true 。
当您在[[ ... ]]
中只编写一个字符串而不使用=
之类的任何运算符时,对于非空字符串,该字符串将被解释为 true ,而 false 表示空字符串。
你可能意味着
[[ "$PROCESS_RUNNING1" = "active" && "$PROCESS_RUNNING2" = "(running)"
|| "$PROCESS_RUNNING2" = "(exited)" ]]
或甚至更可能是带括号的版本
[[ "$PROCESS_RUNNING1" = "active" &&
("$PROCESS_RUNNING2" = "(running)" || "$PROCESS_RUNNING2" = "(exited)") ]]
确保第一个条件始终保持不变。
PROCESS_STATUS=$(systemctl status "$DAEMON" | awk 'FNR==3')
PROCESS_RUNNING1=$(systemctl status "$DAEMON" | awk 'FNR==3' | awk '{print $2}')
PROCESS_RUNNING2=$(systemctl status "$DAEMON" | awk 'FNR==3' | awk '{print $3}')
可以更有效地编写
PROCESS_STATUS=$(systemctl status "$DAEMON" | awk 'FNR==3')
PROCESS_RUNNING1=$(awk '{print $2}' <<< "$PROCESS_STATUS")
PROCESS_RUNNING2=$(awk '{print $3}' <<< "$PROCESS_STATUS")
而不是
if [[ $(pgrep -f "$DAEMON" | wc -l) -eq 0 ]]; then
写
if ! pgrep -f "$DAEMON"; then
支票
[[ $PROCESS_RUNNING2 != "(running)" || "(exited)" ]]
总是 true 。即使你的意思是
[[ $PROCESS_RUNNING2 != "(running)" || $PROCESS_RUNNING2 != "(exited)" ]]
为了评估 false ,$PROCESS_RUNNING2
必须同时拥有值"(running)"
和("exited")
。
环境和内置变量用 ALLCAPS 编写。在 camelCase 中编写自己的变量,以避免名称冲突。