Shell常用脚本:监控本机内存使用率

x33g5p2x  于2022-02-18 转载在 Shell  
字(1.2k)|赞(0)|评价(0)|浏览(665)

free内存不够,则从buffer、cache中取内存概念total:总内存,物理内存总数used:已经使用的内存数free:空闲的内存数shared:多个进程共享的内存数buffer、cache:缓存内存数available:还可以被应用程序使用的物理内存大小 == 约等于 free + buffer + cacheswap:虚拟内存

方案1 == free命令

memoryInfo.sh

#!/bin/bash

totalMemory=$(free | awk 'NR==2{print $2}')
usedMemory=$(free | awk 'NR==2{print $3}')
freeMemory=$(free | awk 'NR==2{print $4}')
cachedMemory=$(free | awk 'NR==2{print $6}')

# echo -e "总内存: $(($totalMemory/1024/1024))GB"
echo -e "总内存: $(printf "%.2f" `echo "scale=2;$totalMemory/1024/1024"|bc`)GB"
echo -e "内存利用率: $(($usedMemory * 100 / $totalMemory)) %"
echo -e "缓存利用率: $(($cachedMemory * 100 / $totalMemory)) %"
echo -e "剩余内存率: $(($freeMemory * 100 / $totalMemory)) %"

方案2 == /proc/meminfo文件

memoryRate2.sh

#!/bin/bash

totalMemory=$( head -9 /proc/meminfo | awk 'NR==1{print $2}')
usedMemory=$( head -9 /proc/meminfo | awk 'NR==9{print $2}')
freeMemory=$( head -9 /proc/meminfo | awk 'NR==2{print $2}')
cachedMemory=$( head -9 /proc/meminfo | awk 'NR==4{buffers=$2}NR==5{print buffers+$2}')

# echo $totalMemory;
# echo $usedMemory;
# echo $freeMemory;
# echo $cachedMemory;

echo -e "usedMemoryRate: $(($usedMemory * 100 / $totalMemory)) %"
echo -e "cachedMemoryRate: $(($cachedMemory * 100 / $totalMemory)) %"
echo -e "freeMemoryRate: $(($freeMemory * 100 / $totalMemory)) %"

相关文章