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 ")

相關內容