Automation Script and Explanation
Automation Script and Explanation
Script
#!/bin/bash
free -wh > ~/old
purging () {
sudo sync; sudo echo 1 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 1 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 1 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 2 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 2 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 2 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 3 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 3 > /proc/sys/vm/drop_caches
sudo sync; sudo echo 3 > /proc/sys/vm/drop_caches
}
report(){
echo -e "\n\n\n\nServer $(curl -s -4 ident.me;echo)'s cache Purging report:-\n-----Before Purging--
--\n$(cat ~/old)\n\n-----After Purging-----\n$(free -wh)\nTimeStamp:- $(TZ='Asia/Kolkata'
date)\n\n"
}
purging > /dev/null 2>&1 && report || echo -e "Kindly run with sudo rights\nExample:- sudo
mfree"
Explanation
Line 1: #!/bin/bash
• This is the shebang line, which tells the operating system to use the Bash shell to
interpret and execute the following script.
• The output is redirected to a file named old in the user's home directory.
• This creates a snapshot of memory usage before the purging process, serving as
a reference point for comparison.
▪ sudo sync: Forces the system to write all data from memory to
disk.
Line 16: purging > /dev/null 2>&1 && report || echo -e "Kindly run with sudo
rights\nExample:- sudo mfree"
o > /dev/null: Discards the standard output, preventing it from cluttering the
terminal.
o 2>&1: Redirects standard error to standard output, allowing both outputs
to be handled together.
• If the function execution succeeds (&&), the report function is called to generate
a report.
Important Cautions:
• Execute with caution: Aggressive cache clearing can negatively impact system
performance. Consider alternative approaches like targeted cache invalidation
or memory management tools.
If you want to execute this script on every Sunday at 6pm then you can update like this
in crontab:
0 18 * * 0 /path/to/your/script.sh
Explanation: