思路
用free -m命令查看系统内存的使用率,用(total-free)*100/total即可得到已用的百分比
[root@liyili lianxi]# free -m
total used free shared buff/cache available
Mem: 1819 232 1426 9 159 1434
Swap: 2047 0 2047
[root@liyili lianxi]#
现在来看具体的脚本实现
#!/bin/bash
#总的内存大小
mem_total=$(free -m|head -2|tail -1|awk '{print $2}')
#剩余的内存大小
mem_free=$(free -m|head -2|tail -1|awk '{print $4}')
num=$(echo "scale=2;($mem_total - $mem_free) * 100/$mem_total"|bc)
result=$(echo "$num > 70"|bc)
if (( $result == 1 ))
then
echo "内存使用率超过70%!现在的内存使用率是 $num %"
else
echo "内存还够用,现在的内存使用率是 $num %"
fi
注意
由于计算的过程涉及到小数,需要使用bc工具来帮助计算结果
(没有安装的使用下面这条命令来安装)
yum install bc -y