Linux Desktop GuideLinux System Administration

How to Clear RAM Memory Cache, Buffer and Swap Space on Linux

This guide shows how to safely clear RAM memory cache, buffers and swap space on Linux using the kernel's drop_caches interface and swap tools. It covers prerequisites, the commands you’ll use, a reusable script, a cron example, verification steps, and troubleshooting. Keywords: clear RAM cache Linux, drop_caches, clear swap Linux are used naturally throughout.

Prerequisites

  • You must have root privileges (use sudo) to modify kernel parameters or control swap devices.
  • Understand the risk: clearing caches is normally unnecessary and can slow your system temporarily; do not schedule automatic cache drops on production servers unless you fully understand the impact.
  • Have console access or SSH and a working shell (bash/sh).

Quick verification: check current memory and swap

Before making changes, check memory and swap usage with free. This shows totals, used, free, and cached memory.

free -h
              total        used        free      shared  buff/cache   available
Mem:           15Gi        9.2Gi       1.1Gi       184Mi       4.7Gi       5.9Gi
Swap:          2.0Gi       512Mi       1.5Gi

Explanation: free -h prints memory usage in human-readable units. We'll use this to compare before and after cache drops.

How the kernel cache works (brief)

Linux uses unused RAM to cache files (pagecache) and metadata (dentries and inodes). Freeing that cache manually is rarely needed; it is most useful for testing I/O benchmarks or recovering memory in exceptional cases. The kernel will reuse freed memory as needed.

Clearing PageCache only (safe option)

To clear just the pagecache (cached file contents) without touching dentries and inodes, run sync and write 1 to /proc/sys/vm/drop_caches. Use a method that preserves sudo privileges for the redirect.

sync; echo 1 | sudo tee /proc/sys/vm/drop_caches
1

Explanation:

  • sync flushes filesystem buffers to disk so you don’t lose data. It produces no output.
  • echo 1 | sudo tee /proc/sys/vm/drop_caches writes the value 1 into the kernel control file to free PageCache. We use tee with sudo to avoid a shell redirection permission problem.

Verify the effect with free -h again:

free -h
              total        used        free      shared  buff/cache   available
Mem:           15Gi        9.4Gi       2.8Gi       184Mi       3.0Gi       6.6Gi
Swap:          2.0Gi       512Mi       1.5Gi

Explanation: Notice buff/cache decreased after dropping pagecache. Actual numbers vary by system.

Clearing dentries and inodes

To clear directory entries (dentries) and inode caches only, write 2 to /proc/sys/vm/drop_caches (again, run sync first).

sync; echo 2 | sudo tee /proc/sys/vm/drop_caches
2

Explanation: 2 tells the kernel to free dentries and inodes. Use this when testing metadata-heavy operations. This is less commonly needed than pagecache drops.

Clear PageCache, dentries and inodes (all)

To clear everything (pagecache + dentries + inodes) use 3. This is the most aggressive option and not recommended on production systems without careful planning.

sync; echo 3 | sudo tee /proc/sys/vm/drop_caches
3

Explanation: 3 = 1 (pagecache) + 2 (dentries and inodes). It will cause the system to re-read metadata and file contents from disk as required, potentially slowing the system briefly.

Common permission error and safe alternatives

If you attempt a naive redirect as a non-root user you’ll see a permission error:

echo 1 > /proc/sys/vm/drop_caches
bash: /proc/sys/vm/drop_caches: Permission denied

Fix: either run the entire command in a root shell or use tee as shown earlier:

sudo sh -c 'sync; echo 1 > /proc/sys/vm/drop_caches'

or

sync; echo 1 | sudo tee /proc/sys/vm/drop_caches
1

Explanation: The shell handles the redirection before sudo runs, so a simple sudo before echo won’t elevate the redirect. Using sh -c or piping into sudo tee avoids that issue.

How to clear Swap space

Clearing swap involves turning swap off and then back on. This moves swapped pages back into RAM, so ensure you have enough free RAM before doing this. Typical sequence:

sudo swapon --show
NAME      TYPE  SIZE   USED PRIO
/swapfile file  2G     512M   -2

Explanation: swapon –show lists active swap devices/files and usage. Use this to confirm current swap usage.

sudo swapoff -a

Explanation: swapoff -a disables all swap. It usually produces no stdout but may log to syslog. If the system doesn't have enough free RAM, swapoff can fail or cause memory pressure—do not run on low-memory systems without testing.

sudo swapon --show
# no output (no active swap devices)

Explanation: After swapoff, swapon –show should show nothing if swap has been successfully disabled.

sudo swapon -a
sudo swapon --show
NAME      TYPE  SIZE   USED PRIO
/swapfile file  2G     0B     -2

Explanation: swapon -a re-enables swap devices as configured in /etc/fstab. After re-enabling, verify the swap usage again with swapon –show.

Create a reusable script to clear cache and swap

You can combine the above into a script and run it manually when needed. Example script at /usr/local/sbin/clearcache.sh:

sudo tee /usr/local/sbin/clearcache.sh > /dev/null <<'EOF' #!/bin/bash # clearcache.sh - clear pagecache, dentries and inodes and reset swap # Run as root (via sudo) # Flush filesystem buffers sync # Free pagecache, dentries and inodes echo 3 > /proc/sys/vm/drop_caches

# Disable and re-enable swap
swapoff -a
swapon -a
EOF

Now make the script executable and verify its presence:

sudo chmod +x /usr/local/sbin/clearcache.sh
ls -l /usr/local/sbin/clearcache.sh
-rwxr-xr-x 1 root root 234 Mar  2 14:00 /usr/local/sbin/clearcache.sh

Explanation:

  • /usr/local/sbin/clearcache.sh is a central, root-owned script location for administrative tools.
  • chmod +x makes the script executable.
  • Using a script centralizes the logic and reduces the chance of typing mistakes.

Schedule with cron (NOT recommended for production)

Scheduling automatic cache drops on production systems is generally a bad idea. However, for testing or controlled environments you can create a cron.d drop-in. The example below runs the script daily at 14:00 (2PM):

echo "0 14 * * * root /usr/local/sbin/clearcache.sh" | sudo tee /etc/cron.d/clearcache
0 14 * * * root /usr/local/sbin/clearcache.sh
sudo cat /etc/cron.d/clearcache
0 14 * * * root /usr/local/sbin/clearcache.sh

Explanation: Creating a file under /etc/cron.d registers a system cron job. Include the username field (root) since files in /etc/cron.d follow the system crontab format.

Verification checklist

After running the script manually or via cron, verify changes:

free -h
              total        used        free      shared  buff/cache   available
Mem:           15Gi        10Gi        1.3Gi      184Mi       3.7Gi       5.1Gi
Swap:          2.0Gi       0B          2.0Gi
sudo swapon --show
NAME      TYPE  SIZE   USED PRIO
/swapfile file  2G     0B     -2

Explanation: Confirm buff/cache has been reduced and swap usage is back to expected levels (often 0B immediately after swapoff/swapon).

Troubleshooting

  • Permission denied when writing to /proc/sys/vm/drop_caches: use sudo sh -c ‘…’ or echo VALUE | sudo tee ….
  • swapoff fails: ensure sufficient free RAM; check processes with high memory use (top or ps aux –sort=-%mem).
  • Unexpected slowdowns after dropping caches: this is normal until the kernel repopulates caches from disk.
  • Do not run automatic cache clears when heavy traffic or backups are running.

Useful diagnostic commands

cat /proc/sys/vm/drop_caches
0

Explanation: Shows last value written to the control file. Kernel resets it to 0 automatically; the written value is a command, not a persistent setting.

cat /proc/meminfo | grep -E 'MemTotal|MemFree|Buffers|Cached|SwapTotal|SwapFree'
MemTotal:       15728640 kB
MemFree:         1126400 kB
Buffers:          483200 kB
Cached:         3123456 kB
SwapTotal:       2097148 kB
SwapFree:        2097148 kB

Explanation: /proc/meminfo gives low-level memory statistics useful for troubleshooting memory pressure.

Should you clear RAM cache automatically on production?

Short answer: No, unless you have a very specific, tested reason. Automatic drops can cause disk I/O spikes and slow your services when caches are repopulated. Use the techniques above for manual troubleshooting, benchmarking, and controlled maintenance windows only.

Conclusion

Clearing RAM memory cache, buffers and swap on Linux is straightforward using drop_caches and swap control utilities (swapoff/swapon). Use the safe option (pagecache only) when possible, and avoid automating cache clears on production servers. For quick checks and verification, use free -h, swapon –show, and /proc/meminfo. Keywords: clear RAM cache Linux, drop_caches, clear swap Linux.

Komentariši

Vaša email adresa neće biti objavljivana. Neophodna polja su označena sa *