方法一:
#!/bin/bash

mem=free -m |grep Mem |awk '{print $3/$2*100}' |awk -F"." '{print $1}'

if [ $mem -ge 80 ];then
echo "Memory usage exceeds 80%."
read -p "Do you want to clean up the memory? [y/n] " answer
if [ $answer = y ];then
echo 3 > /proc/sys/vm/drop_caches
echo "Memory cleaning completion."
elif [ $answer = n ];then
echo "Exit."
else
echo "Input error."
fi
else
echo "The rate of use of memory is $mem%."
fi

方法二:
#!/bin/bash

#free -m | awk NR==2'{print $2}' 筛选内存的第二行第二列
#注意:NR==2与'{print $2}'之间没有空格
total=free -m | awk NR==2'{print $2}'
used=free -m | awk NR==2'{print $3}'
mem_used=echo "$[ ${used}*100/${total} ]"
if [ ${mem_used} -ge "80" ];then
wall "More than 80% of the current memory is used, and the current memory is ${mem_used}%."
else
echo "${mem_used}"
fi

思路:
检测内存的使用率_第1张图片