Knowledge Base Hub

Browse through our helpful how-to guides to get the fastest solutions to your technical issues.

Home  >  How-Tos  >  Clear Linux Cache Safely: RAM, Swap & Temp Files Explained

Clear Linux Cache Safely: RAM, Swap & Temp Files Explained

 7 min

What is Cache in Linux?

In Linux, cache refers to a type of memory that saves frequently accessed information, files, and instructions to boost performance. This includes: 

  1. Page Cache: Holds the contents of files and programs that have previously been read from the disk. 
  2. Dentries and Inodes: Cache information about directories and files. 
  3. Swap Space: A section of the hard disk used as virtual storage when the RAM is filled. 
  4. Buffers: Memory locations set aside temporarily for data on the route to or from hardware devices. 

Linux takes care of caching on its own to enhance data retrieval speed and system performance. However, these cached files can become stale or obsolete over time.

Why Clear Cache in Linux?

As previously mentioned, improved performance is a result of cache; however, there are instances where clearing it can be a necessity:

  1. Clearing Up Memory: In case the system is running low on RAM, clearing the cache can assist in regaining some memory. 
  2. Resolving Problems: Due to corrupted or outdated data caches, applications may sometimes not function properly. 
  3. Strategic Cache Cleansing: For users on resource-constrained systems, it may be beneficial to their overall performance to free Linux cache memory from time to time. 

Related Read: How to Clear Cache in Android?

Types of Caches in Linux Operating System

To enhance system performance, Linux integrates many types of caches. The kernel maintains control of every cache to make certain that memory is used efficiently, and every cache has its own role.

Similar Suggestion: How to Clear Cache in Laravel?

A. RAM Memory Cache

1. PageCache

Allows much faster repeat access by storing the file content read from the disk. 

2. Dentries

Improving directory traversal, this cache stores directory path lookups. Dentries is short for “directory entries.” 

3. Inodes

Holds information about a file’s metadata, including its size, permissions, and timestamps. 

These three parts are what constitute the majority of memory cache in Linux and enhance the effectiveness of the system significantly. 

B. Swap Space Cache 

When RAM is full, swap is a space on disk that is used. Although not a direct command to clear cache in Linux, it’s closely tied to memory management. When system memory is low, pages of memory that are not being used as much are moved to swap to free RAM for processes that need to be active. 

C. Buffer Cache 

The buffer cache is the section of RAM set aside for temporarily storing data that is in transit to and from input/output devices like hard disks or USB drives. It manages data at the block level, as opposed to PageCache, which handles files. 

Buffer cache is closely linked with PageCache and is often grouped (command to clear cache in Linux ) when discussing RAM-based caching. It plays a critical role in facilitating read and write request handling and minimizing disk access latencies.

Checking RAM Cache In Linux 

It is recommended to assess the amount of memory used for caching before clearing the cache. There are some basic-level tools in Linux to track memory usage and also inclusive of cached memory. 

  • With the free -h Command

You can easily check your RAM cache using the free -h clear cache command in Linux. It’s one of the simplest ways to see your system’s memory usage.

Command: free -h

Sample Output:

totalusedfreesharedbuff/cacheavailable
Mem:7.7G2.5G1.2G150M4.0G4.7G
Swap:2.0G0B2.0G

Definition of Output:

  1. total: is the total physical RAM of the system.
  2. used: Memory, which is inhabited by processes. 
  3. free: Memory that is unused fully. 
  4. shared: Memory shared by more than one process is known as (mostly used by) tmpfs. 
  5. buff/cache: In this column, the memory usage in the buffer and cache is enumerated. This compartment contains PageCache, Dentries, and Inodes. Reclaimable memory will be given when required.
  6. available: gives the value of memory that can be utilized without swapping. 
  7. used: It provides a roundabout value of how much memory is spent for loading in new applications concerning a swap disk.

Step-by-Step Guide to Clearing Cache

As with most Linux operating procedures, clearing the cache is a straightforward and safe task when performed correctly. A description outlining the steps of clearing various types of system cache is given below.

Related Read: How To Clear WordPress Cache?

A. Resetting RAM Memory Cache

The drop_caches interface allows the memory cache to be reset within Linux. Such an operation does not require the system to be restarted and does not influence active processes. You can ensure all pending disk writes are flushed by using the below command: 

sync

1. Resetting PageCache Alone

echo 1 > /proc/sys/vm/drop_caches 

Explanation: This command notifies the kernel to free the file contents stored in the RAM-Aprile cache known as PageCache. It has no impact on Dentries and Inodes.

2. Resetting Dentries and Inodes Exclusively

echo 2 > /proc/sys/vm/drop_caches

Explanation: Dentries (directory entries) alongside Inodes (metadata about files) get removed. Such an operation is important when there becomes obsolete file system metadata.

3. Resetting All Caches (PageCache, Dentries, Inodes)

echo 3 > /proc/sys/vm/drop_caches

Explanation: Clears everything — file contents, directory entries, and metadata. As previously stated, these commands need to be executed under root privileges or with sudo.

For example, with sudo: 

sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'

B. Clearing Cache from the Swap Space

1. Disabling Swap

To clear swap space, first, you should turn it off:

sudo swapoff -a

Explanation: This command turns off all swap devices. If there is sufficient RAM available, the swap data is copied back into RAM.

2. Turning On Swap

After performing these steps, you can turn on swap space again:

sudo swapon -a

Explanation: This action enables all the configured swap devices and files. This means the system has the ability to utilize swap space once again.

3. Change Swappiness (Optional but Related)

Swappiness is a kernel variable that states how aggressively the Linux system wants to use the swap space. They can have values between 0 and 100.

  • Lower value = less swapping (RAM resource usage preference)
  • Higher value = more swapping

To see the current swap enabled:

Check current swappiness:

cat /proc/sys/vm/swappiness

Set swappiness to a lower value (e.g., 10):

sudo sysctl vm.swappiness=10

To make it permanent, add the following line to /etc/sysctl.conf:

vm.swappiness=10

The Automation Process: Clear Cache in Linux

For some environments, like memory-limited servers, automating the clearing of the cache could help with achieving a certain performance level. Cron jobs can be applied for this purpose, to schedule tasks to run at user-defined intervals. 

Different Types Of Cron Jobs

Using a cron job, you can schedule the cache to be cleared at designated time intervals, for example, weekly or daily. This approach should be taken with a lot of forethought since overly effective performance in general can be very counterproductive.

Example: Clearing All Caches Every Day Using A Cron Job

To start, log into the crontab editor:

sudo crontab -e

Next, add the following line to the crontab so that the cache-clearing scripts are run once every day at 3 AM:

0 3 * * * sync; echo 3 > /proc/sys/vm/drop_caches

Explanation:

0 3 * * * = Run it at exactly 3:00 AM every day.

Before clearing the cache, sync ensures that all disk writes are completed.

Clearing PageCache, Dentries, and Inodes is done by: 

echo 3 > /proc/sys/vm/drop_caches.

Tip: You can improve maintainability by moving the cache-clearing command into a shell script (for example, /usr/local/bin/clear_cache.sh) and executing it from the cron job.

Conclusion

The important benefit of clearing the cache in your Linux system is an increase in system response time. This is especially helpful when system resources are limited. Clearing the cache removes any stale data, which helps improve the overall calculation of memory, manage the amount of swap used, and permanently improve the system responsiveness.

FAQs

1. How can I clear the RAM cache page in Linux?

As a root user, executing the command below will enable you to clear the cache in Linux (page cache), which stores file content in memory: For the process of clearing page caches to be achieved, all operations to be completed must be shackled so that they can be bound in a disk, during which the base active command minimizes the structure of the base function during the purge.

2. What is the meaning of temp files and how can one remove them in Linux?

Applications and the system store data that is short in terms of duration in temp files. On a deeper level, temp files can be found within the /tmp directory, var/tmp, and caches belonging to individual users. Apart from Stacer, easier commands such as rm -rf /tmp/* or dow doser can work better and faster in clearing temp files.

3. Will clearing caches improve my Linux system’s performance?

Removing caches might temporarily relieve a bit of memory, particularly in low-RAM environments, but it doesn’t help the system perform better. Linux caches are built to make access to already stored files faster. If you are not under a memory pressure situation, excessive clearing of the cache can lead to poorer performance due to an increased need for data retrieval from the disk.

4. Are there any automated tools or scripts for clearing caches in Linux?

Of course, you can use cron jobs or even simple shell scripts to automate cache-clearing tasks. An example would be a script with sync; echo 3 > /proc/sys/vm/drop_caches that can be configured to run through crontab. Furthermore, system maintenance applications such as BleachBit, Stacer, and Autoclean (for package caches) can cleanse various system caches and temporary files autonomously.

For our Knowledge Base visitors only
Get 10% OFF on Hosting
Special Offer!
30
MINS
59
SECS
Claim the discount before it’s too late. Use the coupon code:
STORYSAVER
Note: Copy the coupon code and apply it on checkout.