Table of Contents
This article will provide to you a script automatically frees up memory in Linux. This script is for Linux servers.
Commands to clear cache in Linux
You know, most of the memory in Linux will turn into cache during operation.
Linux provides the following three commands to clear the cache at different levels.
1. Command to clear PageCache only.
sync; echo 1 > /proc/sys/vm/drop_caches2. Command to clear dentries and inodes.
sync; echo 2 > /proc/sys/vm/drop_caches3. Command to clear PageCache, dentries and inodes.
sync; echo 3 > /proc/sys/vm/drop_cachesMy script will use the 3rd command above, you can edit it according to your needs.
Script automatically frees up memory
At this point, you can completely think that just using the above command is done, using the script for what.
Recommended Reading: Calculate percent of memory used in Linux
The problem is, Linux server works 24/24 and I can’t wake up 24/24. I need a tool to monitor server memory. I need it to automatically free the server’s memory if the memory exceeds a certain threshold (which I will declare).
My script will do the following two things.
- Every 1 minute, this script will check % of server memory usage (run through crontab).
- Automatically free memory if it exceeds 80% of memory.
Download the script and use it

Use the following command to download the script to your server.
wget https://gitlab.com/Danny_Pham/WriteBash.com/raw/master/Utilities/06-Script_automatically_free_up_memory.sh -O /opt/script_auto_free_memory.shNext, grant the script permission.
chmod 0700 /opt/script_auto_free_memory.shThere are two ways you can use this script.
Recommended Reading: Script free disk space from deleted files
Using the manual, you can type one of the following commands to execute the script manually.
bash /opt/script_auto_free_memory.shOr:
/opt/script_auto_free_memory.shRun the script automatically with crontab
The obvious thing here is that you want the script to work automatically, not manually.
We use crontab in Linux, setting it to automatically execute the script once every minute.
crontab -l | { cat; echo "# Check memory used every 1 minute & auto frees up memory if it over 80%"; } | crontab -
crontab -l | { cat; echo "*/1 * * * * /opt/script_auto_free_memory.sh"; } | crontab -Conclusion
A simple script that will be very effective for your work. The services on the server now need a lot of memory, and if you don’t pay attention, memory overflow is possible. At that time, your service will be interrupted.
(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).