How to Improve System Performance: Clear Linux Cache Easily Bash Script
Keeping your Linux computer running fast is important. Sometimes Clear Linux Cache, memory gets full because of cached files. This can slow down your system. This article will show you how to clear the cache easily using a simple script.
Clear Linux Cache Easily Bash Script Objective :
- Understand why clearing the cache is helpful.
- How to automate clearing the cache with a script.
- Make your system run faster by managing memory better.
Clear Linux Cache Easily Bash Script Prerequisites :
- Basic knowledge of Linux commands.
- Permission to run system commands as root or with sudo.
Notes :
- Please change the threshold values according to your requirements.
- Understand each command before executing the script to ensure it fits your environment and requirements.
ALSO READ :
- Automating Linux monitor memory usage script
- How to install Linux Server Monitoring tool Nagios XI and NCPA
- How to Automating User Switch in Shell Scripts with Nopasswd Sudoers
Example output :
Stage | Output |
Before Clearing Cache | Memory usage: 85% |
total used free shared buff/cache available | |
2000 1700 100 50 200 150 | |
After Clearing Cache | Memory usage: 50% |
total used free shared buff/cache available | |
2000 1000 800 50 200 1200 |
Script :
#!/bin/bash ################################################################# # Date: 15-July-2024 # Author: Krishna Tummeti # Website: Tech Base Hub # Purpose: Improve System Performance: Clear Linux Cache Easily Bash Script ################################################################# # Get memory usage as a percentage mem_usage=$(free -m | awk 'NR==2 {print int($3*100/$2)}') # Set threshold threshold=80 # Check if memory usage is greater than or equal to threshold if [[ $mem_usage -ge $threshold ]] then # Clear page cache sync; echo 1 > /proc/sys/vm/drop_caches # Clear dentries and inodes sync; echo 2 > /proc/sys/vm/drop_caches # Clear page cache, dentries, and inodes sync; echo 3 > /proc/sys/vm/drop_caches # Restart swap swapoff -a && swapon -a else # Exit with status 1 if memory usage is below threshold exit 1 fi
We have successfully executed the script to clear the cache and refresh the swap.
Thank You