【Linux】 Linux 释放内存脚本

在Linux系统中,通常不需要手动释放内存到操作系统,因为Linux内核会自动管理内存。不过在经常会遇到内存不足,系统应用运行效率低的情况

编写一个脚本来"释放"内存,可以通过调用sync命令同步磁盘,并通过echo命令写入特定值到/proc/sys/vm/drop_caches来清理缓存。
下面是一个简单的shell脚本示例,用于释放页缓存、dentries和inodes:

shell 复制代码
#!/bin/bash
##################
#author:7731226@qq.com#
##################
#系统分配的区总量  
mem_total=`free -m |grep Mem | awk '{print  $2}'` 
  
#当前剩余的free大小  
mem_free=`free -m |grep Mem | awk '{print  $4}'` 
  
#当前已使用的used大小  
mem_used=`free -m |grep Mem | awk '{print  $3}'` 
  
  
if (($mem_used !=0)); then 
  
#如果已被使用,则计算当前剩余free所占总量的百分比,用小数来表示,要在小数点前面补一个整数位0  
   mem_per=0`echo "scale=2;$mem_free/$mem_total" | bc` 
   DATA="$(date -d today +"%Y-%m-%d-%H-%M") free percent is : $mem_per"
   echo $DATA >>/var/log/mem_detect.log
#设置的告警值为20%(即使用超过80%的时候告警)。  
   mem_warn=0.20 
  
#当前剩余百分比与告警值进行比较(当大于告警值(即剩余20%以上)时会返回1,小于(即剩余不足20%)时会返回0 )  
   mem_now=`expr $mem_per \> $mem_warn` 
  
#如果当前使用超过80%(即剩余小于20%,上面的返回值等于0),释放内存
  if (($mem_now == 0)); then 
      sync 
      sync 
      echo 1 > /proc/sys/vm/drop_caches 
      # To free dentries and inodes: 
      echo 2 > /proc/sys/vm/drop_caches 
      # To free pagecache, dentries andinodes: 
      echo 3 > /proc/sys/vm/drop_caches
  fi
fi

添加定时任务:

shell 复制代码
10 * * * *  /root/recover_mem.sh 
相关推荐
姓刘的哦1 分钟前
大模型祛魅
linux
Shota Kishi16 分钟前
SLV 新增 allnodes-jito 支持:Solana 验证者多客户端运维与 AI agent 自动化解析
运维·自动化·区块链
hj2862511 小时前
linux下一步学习内容
linux·运维
睡不醒男孩0308232 小时前
数据库高可用运维实操指南:基于CLup的PostgreSQL生产环境自动化管理
运维·数据库·postgresql
V搜xhliang02462 小时前
临床科研新范式:从选题到投稿,AI智能体如何接管全流程?
运维·数据结构·人工智能·算法·microsoft·数据挖掘·自动化
tudoSearcher2 小时前
日志、指标、链路追踪:可观测性三支柱深度解析
运维·服务器·网络·prometheus
xier_ran2 小时前
【infra之路】Linux基础命令与系统排查
linux·运维·服务器
zh路西法2 小时前
【Linux 串口通信】基于 C++ 多线程的同步/异步串口实现
linux·运维·c++·python
c238562 小时前
linux基础2
linux·运维·服务器
子兮曰3 小时前
WSL 配 GPU 用 Docker 的折腾指南(2026 年版)
linux·前端·后端