Skip to content

Instantly share code, notes, and snippets.

@PSJoshi
Created August 23, 2022 09:58
Show Gist options
  • Save PSJoshi/d180c02c7fe91c2c53330292db9a3a5a to your computer and use it in GitHub Desktop.
Save PSJoshi/d180c02c7fe91c2c53330292db9a3a5a to your computer and use it in GitHub Desktop.
Clear RAM cache and Swap space

Clear RAM-cache and Swap in Linux

It is possible to clear cache without interrupting any process or service. sync will flush the file system buffer and drop_cache will clean cache without killing any application/service.

Clear PageCache only

# sync; echo 1 > /proc/sys/vm/drop_caches

Clear inodes

# sync; echo 2 > /proc/sys/vm/drop_caches

Clear both (it's not recommended on production!)

# sync; echo 3 > /proc/sys/vm/drop_caches
  • clear swap
# swapoff -a && swapon -a
  • clearcache.sh
#!/bin/bash
echo "echo 1 > /proc/sys/vm/drop_caches" && swapoff -a && swapon -a && printf '\n Ram-cache and Swap cleared'

Add executable permission

chmod 755 clearcache.sh

Add cron job

crontab -l > cron_backup
echo "0 10 * * * sudo /home/<user>/clearcache.sh >/dev/null 2>&1" >> cron_backup
crontab cron_backup
rm cron_backup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment