linux通过脚本获取内存信息
1 原理
脚本中通过执行free获取内存信息,然后将文本信息通过“空格”分隔符分割成字符串数组将不同信息提取出来,最后通过bc计算出百分比
2 脚本
#!/bin/sh
HOSTNAME=`hostname -s`
echo "==============hostname================"
echo "hostname=$HOSTNAME"
MEMORYLINE=`free | grep Mem`
#字符串转数组
MEMORYARR=($MEMORYLINE)
echo "==============memory=================="
total=${MEMORYARR[1]}
used=${MEMORYARR[2]}
echo "total = $total"
echo "used = $used"
#计算百分比
used_pre=`echo "scale=2;$used*100/$total" | bc`
echo "used_pre = $used_pre"%
free=${MEMORYARR[3]}
echo "free = $free"
free_pre=`echo "scale=2;$free*100/$total" | bc`
echo "free_pre = $free_pre"%
echo "================CPU==================="