if 语句中的两个条件

if 语句中的两个条件

我正在努力理解 if 语句

我希望每当内存使用率或 CPU 使用率超过 70% 时,就会弹出“系统利用率过高”的消息,现在我在 if 语句中尝试了以下 2 个条件,但它给出了错误。

# This script monitors CPU and memory usage
RED='\033[0;31m'
NC='\033[0m' # No Color


while :
do
  # Get the current usage of CPU and memory

  limit=70.0
  cpuUsage=$(top -bn1 | awk '/Cpu/ { print $2}')
  memTotal=$(free -m | awk '/Mem/{print $2}')
  memUsage=$(free -m | awk '/Mem/{print $3}')
  memUsage=$(( (memUsage * 100) / memTotal ))

  # Print the usage
  echo "CPU Usage: $cpuUsage%"
  echo "Memory Usage: $memUsage%"
  # Sleep for 1 second
  sleep 1

  if  (( $(echo "$cpuUsage > $limit ; $memUsage > $limit" |bc -l) ))
  then
         printf "${RED}The system is highly utilized${NC}\n"
  else
        echo The system is not highly utilized
  fi
done

据我所知,; 运行会检查第一个条件,然后无论成功与否都会转到第二个条件。无论如何我都会收到此错误:0:表达式中的语法错误(错误标记是“0”)

答案1

bc理解||&&

if (( $(echo "$cpuUsage > $limit || $memUsage > $limit" | bc -l) ))

答案2

尽管(如您所见),您可以在 GNU bc(以及 busybox bc)中使用逻辑组合表达式,但 POSIX 1||不支持它。

由于您已经在使用 awk 来解析topfree输出,因此另一种方法是在 awk 中执行算术和关系测试 - 然后您可以在 shell 中使用简单的整数比较(甚至不需要 bash):

#!/bin/sh

# This script monitors CPU and memory usage

RED='\033[0;31m'
NC='\033[0m' # No Color

limit=${1:-70.0}

while :
do
  # Get the current usage of CPU and memory
  top -bn1 | awk -v limit="$limit" '
    /^%Cpu/ {printf "CPU Usage: %.1f%%\n", $2; exit ($2+0 > limit ? 1 : 0)} 
  '
  cpuHi=$?

  free -m | awk -v limit="$limit" '
    /^Mem/ {usage = 100*$3/$2; printf "Memory Usage: %.0f%%\n", usage; exit (usage > limit ? 1 : 0)}
  '
  memHi=$?

  sleep 1

  if [ "$cpuHi" -ne 0 ] || [ "$memHi" -ne 0 ]
  then
         printf "${RED}The system is highly utilized${NC}\n"
  else
        printf "The system is not highly utilized\n"
  fi

done

  1. 事实上,POSIX bc 甚至不支持条件构造或循环之外的关系运算符,例如:

     $ echo '2 > 1 || 1 > 2' | bc
     1
    

    但启用了警告:

     $ echo '2 > 1 || 1 > 2' | bc -w
     (standard_in) 1: (Warning) || operator
     (standard_in) 2: (Warning) comparison in expression
     1
    

    与 busybox 类似

     $ echo '2 > 1 || 1 > 2' | busybox bc -w
     bc: POSIX does not allow boolean operators; this is bad: ||
     bc: POSIX does not allow comparison operators outside if or loops
     1
    

答案3

稍微扩展一下@choroba 的回答:

echo "$cpuUsage > $limit ; $memUsage > $limit" |bc -l

将输出2 行

示范

$ set -x
+ set -x
$ ans=$(echo "1==1; 2==1" | bc -l)
++ bc -l
++ echo '1==1; 2==1'
+ ans='1
0'
$ if (( $ans )); then echo yes; fi
+ ((  1
0  ))
bash: ((: 1
0 : syntax error in expression (error token is "0 ")

相关内容