Ubuntu系统自动清理系统内存脚本和使用方法

在使用Ubuntu系统时会出现内存占用太多,系统卡顿现象,有一种shell脚本可以自动清理系统内存,使用方法如下:

1. 新建脚本文件

 如 /home/hulk/tools/SysTools/memory-monitor.sh

#!/bin/bash

# while [[ true ]]; do
	COMPILE_TIME=`date +"%Y%m%d_%H%M"`
	echo "$COMPILE_TIME"
	echo "$COMPILE_TIME">>/tmp/memory_sunquanyu
	#获取空闲内存,单位MB
	memfree=$(free -m | awk '{print $4}' | sed -n 2p)
	echo "$memfree">>/tmp/memory_sunquanyu
	#内存剩余告警阀值,根据实际情况配置
	max=4096
	# 如果未分配内存值小于等于 max

	if [[ ${memfree} -le ${max} ]]; then
		echo "ttttttt">>/tmp/memory_sunquanyu
	    stress -t 5 --vm 10 --vm-bytes 1024M;
		sleep 1
		# sync;
	else
	 	echo "$COMPILE_TIME"" enough memory to use.">/tmp/memory_sunquanyu
	fi
# 	sleep 300;
# done

脚本中用到了 stress 工具命令,如果没有安装,请执行如下命令安装:

sudo apt install stress

2. 设置自动运行

间隔多久执行编辑脚本

执行如下命令, -e是编辑的意思

sudo crontab -e

第一次执行会弹出编辑工具选择,一般选择2 (VIM编辑工具),回车,在最下面增加一行:

Ubuntu系统自动清理系统内存脚本和使用方法_第1张图片

*/10 * * * * /home/hulk/tools/SysTools/memory-monitor.sh  表示每间隔10分钟执行一次这个系统清理脚本。注意加班呢目录改成你放sh脚本的目录。

3. 测试脚本

可以手动测试下脚本是否可以执行, 适当修改脚本阀值,执行脚本: ./memory-monitor.sh。

hulk@hulk-ThinkCentre-M710t-N000:~/tools/SysTools$ ./memory-monitor.sh 
20230906_1028
hulk@hulk-ThinkCentre-M710t-N000:~/tools/SysTools$ 

脚本下载地址: https://download.csdn.net/download/zhanghao_Hulk/88305259

你可能感兴趣的:(Ubuntu,Linux,ubuntu,linux,运维)