By default settings, Linux has a very efficient way of managing the computer’s RAM to get the best performance out of the resources available on your system.
This approach although is great, but might confuse users as the RAM looks completely occupied in spite of closing all applications. That’s how Linux works. It utilizes available memory to cache the applications from the hard disk drive, in a goal to perform faster.
The same advantage becomes a frustrating ordeal, especially for system administrators who are troubleshooting a PC. The changes applied to the system files in the hard disk may not be read because Linux is loading it from RAM. So, in order to confirm a fix to a problem, it is a good idea to clear the RAM. A reboot will work clear the RAM, but how about wiping the RAM in the same session instead to save time? Let’s take a look.
Clearing RAM in Ubuntu, Linux Mint, and derivatives
Launch Terminal and enter the following command.
sudo sync; echo 3 > /proc/sys/vm/drop_caches
The command ‘sync’ is actually flushing the file system buffer. Command ‘echo’ is doing the job of writing to file and additionally, drop_cache is deleting the cache without killing any application/service. You should immediately see RAM getting freed-up.
Tip: Automate Freeing up RAM by Cron Job
Now that you know how to free up memory on your computer, you may want to automate the clearing memory process in a certain frequency. It can easily be done by applying a cron process. Note that I strongly advise NOT to apply cron job on server machines! It could corrupt the server data. This is to be used only on desktop and laptop PCs.
STEP 1: To get started, launch terminal and enter the following command to install vim. It is a preferred text editor to create sh files.
sudo apt-get install vim
Pay attention to the terminal and enter the root password and ‘Y’ when requested.
STEP 2: Now let’s create an sh file named clearram.sh where we will be adding the script.
STEP 3: In the vim editor, you need to press ‘esc’ key and then press ‘i’ to enter into INSERT mode. Then add the following script to it. The first line below is the Shebang, and then the command which we used to clear RAM.
#!/bin/bash echo "echo 3 > /proc/sys/vm/drop_caches"
Save the sh file and exit out of the vim text editor. To do that type :wq and press enter. vim will save the sh file and exit out to the terminal.
STEP 4: Now enter the following command in the terminal to give read/write permissions.
sudo chmod 755 clearram.sh
STEP 5: Time now to call the crontab command:
sudo crontab -e
STEP 6: Let’s assume that we want to clear the RAM every day at 1 PM.
0 13 * * * /clearram.sh
By default, the new sh file will be created at the top level home directory. You can move it to another place, but do remember the path you give in the above command.