首页 > 解决方案 > 如果 X & ( Y<1 or Z>2 ) 如何正确报告

问题描述

我需要一些关于下面脚本的帮助,当涉及到第三个 elif 时,一切都失败了。我尝试了 < 和 -lt,都失败了。我不知道该怎么办了

#!/bin/bash
currenttime=`date +%H%M`
morning="1800"
evening="2000"
host=127.0.0.1

while true; do
ping -c 1 -w 5 $host &> /dev/null

if [[ $? != 0 && ($currenttime > $evening || $currenttime < $morning) ]] #Ping down, and later than evening, or earlier than morning
then
        echo -e "Ping down, later than evening, earlier than morning"
elif [[ $? != 2 && ($currenttime > $evening || $currenttime < $morning) ]] #Ping up, and (later than evening, or earlier than morning)
then
        echo -e "Ping is up, later than evening, earlier than morning"

elif [[ $? != 0 && ($currenttime < $evening || $currenttime > $morning) ]] #Ping down, and (earlier than evening, or later than morning)
then
        echo -e "Ping is down, and it is earlier than evening or later than morning"

elif [[ $? != 2 && ($currenttime < $evening || $currenttime > $morning) ]] #Ping up,and (earlier than evening, or later than morning)
then
        echo -e "Ping is up and it is earlier than evening, or later than morning"

else
        echo "WTF?"
fi

done

标签: bash

解决方案


对于算术比较,您需要使用-eq,-lt等。来自man bash

  arg1 OP arg2
          OP  is one of -eq, -ne, -lt, -le, -gt, or -ge.  These arithmetic
          binary operators return true if arg1 is equal to, not equal  to,
          less  than, less than or equal to, greater than, or greater than
          or equal to arg2, respectively.  Arg1 and arg2 may  be  positive
          or negative integers.

目前你正在做$currenttime < $evening的是一个字符串比较。


推荐阅读