lin*_*bie 3 command-line bash cpu ram
我在 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
Run Code Online (Sandbox Code Playgroud)
据我所知;运行检查第一个条件,然后无论是否成功都转到第二个条件。无论如何,我收到此错误:0:表达式中的语法错误(错误标记为“0”)
bc
理解||
并且&&
。
if (( $(echo "$cpuUsage > $limit || $memUsage > $limit" | bc -l) ))
Run Code Online (Sandbox Code Playgroud)