Linux clear all cache

How To Clear .Cache Folders and Free Up Space On Your Linux PC

Clean up your cache in a few easy steps!

GNU/Linux has implemented efficient storage management for its users. But have you noticed your Linux system running out of space, filled with unused packages you installed months or years ago? How do find them and remove them? Here are a few valuable tips!

Cache File Location

Cache files are stored in /home/username/.cache which mostly consists of your browser’s data, IDE’s (if you use any ) and other software. Each user has its own data and this can build up exponentially . In order to clear it all it’s recommended to have Disk usage analyzer installed.

Disk Usage Analyzer

Disk Usage Analyzer, formerly known as Baobab, is a graphical disk usage analyzer for the GNOME desktop environment. It was part of gnome-utils, but has been a standalone application since GNOME 3.4.

The software gives the user a graphical representation of a disk drive’s contents. The interface allows for selection of specific parts of filesystem so a single folder, the entire filesystem, and even remote folders and filesystems can be scanned and listed at the folder level.

The graphical representation can be switched between a ‘Rings’ chart and a ‘Treemap’ chart to better suit the content being viewed.

Installation

If you don’t already have Disk Usage Analyzer installed, you first need to install the baobab package:

Clear Cache files and folders

Click on home for your user data .

Click on your second disk i.e Vostro-14-3468 as shown in the image below .

Note: Names will be different on your own computer.

Here, the other disks shown as New Volume / 262 GB volume are formatted disks for a dual boot system, in my case Ubuntu 20.10 and Windows 10.

As you click on it, the Disk Usage Analyzer will start to scan your directory for files and folders. Be patient and allow it to finish. After Disk Usage Analyzer is done scanning your Linux PC for files it shows the live illustration of Linux disk usage as the form of a pie chart.

To see updated changes in your filesystem, you’ll need to refresh the scan as it won’t track these storage changes “live.”

Look in the folder tree structure for .cache, and click on it .

Once you click on the .cache folder, the disk usage analyzer will show you the space it’s consuming graphically on the right side .

  • Find the sub folders inside it which you wish to delete .
  • Right-click each one
  • Select Move to trash / bin
  • Now empty your trash / bin

And you are done!

Do not worry about deleting these folders. It is totally safe and the software will recreate them if and when it needs to.

WARNING!

Do not delete anything from your usr and var directories. usr is used for “user programs”. Usually your package manager installs all the binaries, shared files etc. from all programs here (except config files, which go to /etc).

You can check /usr/bin for binaries, /usr/share for shared files (media, etc), /usr/share/doc for documentation.

There is also an /opt folder, where there are “other” binary programs or programs installed from sources other than the default package manager. Some programs like that (usually compiled) also go to usr/local

/var is usually used for log files, ‘temporary’ files (like mail spool, printer spool, etc), databases, and all other data not tied to a specific user.

Logs are usually in /var/log databases in var/lib (mysql — var/lib/mysql ), etc.

If you liked this article, please follow the author on medium !

Источник

How to Drop/Flush/Clear Cache Memory or RAM in Linux (RedHat/CentOS 7/8) in 6 Best Steps

Table of Contents

Читайте также:  Есть ли журнал событий windows

In this article, I will take you through different steps to drop/flush/clear cache memory in Linux. As you might be aware Linux has very robust Memory Management System but still if you need to clear cache memory due to certain reasons then you need to do it manually.

Someday if you ran into a problem where you find that updated data is not visible or accessible from Page Cache then you might need to clear cache memory once and check if it helps. This is required because once the cache memory is cleared then System has to access the files from Disk and hence you will get the updated data. The only downside is that clearing Cache memory will slow down your systems atleast until the cache re-build takes place.

What is Cache

Cache are usually a small reserve amount of memory used generally for faster access of disk files and directories. This Cache is generally called as Page Cache in Linux.

How Page Cache Works in Linux

Page cache is the main Linux disk Cache used in Linux. System will usually add a page based on User read process request. If the requested page is not available in the Cache then the page will be added to the disk and will be available as long as it is needed. This increases the performance of Input Output Read Operations. The only criteria is that Cache should be enough memory available. Page Cache also needs to be in sync with the disk files as new changes in the file should be synced with Cached data or it will marked as dirty and eventually will be removed from the Page Cache.

How to Check Linux Cache Memory

You might be aware of free command in Linux command line to check the current memory usage of the System. Using this command, you can check the total memory, used memory, cache or buffer memory, available memory etc as can be observed from below output. As you can see from below output, 137 MB is the current buffer/Cache memory.

How to Clear Cache Memory in Linux

Example 1: How to Clear Page Cache Only

If you want to clear your disk cache then you need to run echo 1 > /proc/sys/vm/drop_caches after running sync command as shown below.

Example 2: How to Clear Page Cache Every day through crontab

You can also set a small script in crontab to clear cache memory every day as shown below. Please note that clearing cache memory everyday might slow down your system. Hence this needs to be carefully setup.

Example 3: How to Clear dentries and inodes Only

If you want to clear your dentries and inodes then you need to run echo 2 > /proc/sys/vm/drop_caches after running sync command as shown below.

Example 4: How to Clear dentries and inodes every day through crontab

You can also set a small script in crontab to clear page cache every day as shown below. Please note that clearing cache memory everyday might slow down your system. Hence this needs to be carefully setup.

Example 5: How to Clear Page Cache, dentries and inodes

If you want to clear your all disk cache, dentries and inodes then you need to run echo 3 > /proc/sys/vm/drop_caches after running sync command as shown below.

Example 6: How to Clear Page Cache, dentries and inodes every day through crontab

You can also set a small script in crontab to clear cache memory every day as shown below. Please note that clearing cache memory everyday might slow down your system. Hence this needs to be carefully setup.

Popular Recommendations:-

Источник

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

Like any other operating system, GNU/Linux has implemented memory management efficiently and even more than that. But if any process is eating away your memory and you want to clear it, Linux provides a way to flush or clear ram cache.

How to Clear Cache in Linux?

Every Linux System has three options to clear cache without interrupting any processes or services.

1. Clear PageCache only.

2. Clear dentries and inodes.

3. Clear pagecache, dentries, and inodes.

Explanation of the above command.

sync will flush the file system buffer. Command Separated by “;” run sequentially. The shell waits for each command to terminate before executing the next command in the sequence. As mentioned in the kernel documentation, writing to drop_cache will clean cache without killing any application/service, command echo is doing the job of writing to file.

If you have to clear the disk cache, the first command is safest in enterprise and production as “. echo 1 > ….” will clear the PageCache only. It is not recommended to use the third option above “. echo 3 >” in production until you know what you are doing, as it will clear pagecache, dentries, and inodes.

Читайте также:  Как восстановить систему до заводских настроек windows
Is it a good idea to free Buffer and Cache in Linux that might be used by Linux Kernel?

Free Buffer and Cache in Linux

When you are applying various settings and want to check, if it is actually implemented specially on the I/O-extensive benchmark, then you may need to clear the buffer cache. You can drop cache as explained above without rebooting the System i.e., no downtime required.

Linux is designed in such a way that it looks into the disk cache before looking onto the disk. If it finds the resource in the cache, then the request doesn’t reach the disk. If we clean the cache, the disk cache will be less useful as the OS will look for the resource on the disk.

Moreover, it will also slow the system for a few seconds while the cache is cleaned and every resource required by OS is loaded again in the disk cache.

Now we will be creating a shell script to auto clear RAM cache daily at 2 am via a cron scheduler task. Create a shell script clearcache.sh and add the following lines.

Set execute permission on the clearcache.sh file.

Now you may call the script whenever you are required to clear the ram cache.

Now set a cron to clear RAM cache every day at 2 am. Open crontab for editing.

Append the below line, save and exit to run it at 2 am daily.

For more details on how to cron a job, you may like to check our article on 11 Cron Scheduling Jobs.

Is it a good idea to auto clear the RAM cache on the production server?

Clear RAM Cache on Linux Production Server?

No! it is not. Think of a situation when you have scheduled the script to clear ram cache every day at 2 am. Every day at 2 am the script is executed and it flushes your RAM cache. One day for whatsoever reason may be more than expected users are online on your website and seeking resources from your server.

At the same time, the scheduled script runs and clears everything in the cache. Now all the users are fetching data from the disk. It will result in a server crash and corrupt the database. So clear ram-cache only when required, and known your footsteps, else you are a Cargo Cult System Administrator.

How to Clear Swap Space in Linux?

If you want to clear Swap space, you may like to run the below command.

Also, you may add the above command to a cron script above, after understanding all the associated risks.

Now we will be combining both above commands into one single command to make a proper script to clear RAM Cache and Swap Space.

After testing both the above commands, we will run the command “free -h” before and after running the script and will check the cache.

That’s all for now, if you liked the article, don’t forget to provide us with your valuable feedback in the comments to let us know, what you think is a good idea to clear ram cache and buffer in production and Enterprise?

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

Как освободить память Linux

Как и любая другая операционная система, Linux очень эффективно работает с оперативной памятью. Доступная память свободно распространяется между процессами, неиспользуемые страницы сбрасываются в раздел подкачки на диске, а в случае переполнения памяти, срабатывает специальный механизм, встроенный в ядро, который анализирует все процессы и уничтожает виновника.

Когда любой процесс пишет данные на диск, они сохраняются ядром в отдельном кэше. Очень часто этот кэш занимает достаточно много места. В этой статье мы рассмотрим как освободить память в Linux, а точнее, как очистить созданный программами кэш, а также как вычислить и завершить процессы, которые потребляют больше всего памяти.

Как освободить кэш память в Linux

В каждом дистрибутиве Linux можно использовать три команды чтобы очистить кэш памяти linux. Причем вам не придется завершать никаких процессов. Сначала войдите в консоль от имени суперпользователя:

Затем выполните одну из команд. Очистка кэша PageCache:

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

Очистка inode и dentrie:

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

Очистка inode и dentrie и PageCache:

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

А теперь давайте рассмотрим что происходит при выполнении этих команд.

Утилита sync заставляет систему записать все кэшированные, но еще не записанные данные на диск. Это нужно чтобы освободить как можно больше памяти. По умолчанию данные после записи на диск не удаляются из кэша, это нужно для того, чтобы программа могла быстрее их считать при необходимости.

Читайте также:  Для работы vipnet необходимо установить обновление windows kb3033929

Если не выполнить команду sync мы тоже освободим немного места, но после ее выполнения результат будет лучше.

Символ разделения ; дает знать оболочке, что перед тем как выполнить другую команду, нужно дождаться завершения работы первой. Последняя команда echo 1 > /proc/sys/vm/drop_caches записывает значение 1 в файл /proc/sys/vm/drop_caches. Это дает сигнал ядру, что нужно очистить выбранный нами вид кэша.

Виды кэша в Linux

А теперь давайте рассмотрим виды кэша, которые позволяют очищать эти команды, а также как все это работает.

PageCache или страничный кэш — это место, куда ядро складывает все данные, которые вы записывали или читали из диска. Это очень сильно ускоряет работу системы, так как если программе во второй раз понадобятся те же данные, они просто будут взяты из оперативной памяти. Но по этой причине этот кэш занимает больше всего места.

Посмотреть размер страничного кэша можно с помощью утилиты free. Здесь он показан в последней колонке — cached:

Такой кэш чистить эффективнее и безопаснее всего.

Кэш inode и dentrie тоже относится к файловой системе. Только в него записываются не сами данные, а структура файловой системы, расположение файлов и папок. При запросе расположения файла или содержимого папки ядро формирует специальные структуры, в которых есть вся эта информация. При следующем запросе структуры будут уже сохранены в памяти. Для каждой файловой системы существует свой кэш inode и общий кэш dentrie.

Этот кэш занимает очень мало памяти. Данные представлены в байтах, и как видите, это очень мало. Посмотреть его можно командой:

cat /proc/slabinfo | egrep dentry\|inode

Очищать его чтобы освободить память linux не рекомендуется, так как памяти потребляется немного, а на новое сканирование файловой системы идет относительно много времени.

Нужно ли очищать кэш вообще?

Во-первых, если занято очень много памяти, вы можете очистить страничный кэш, особенно если это он занимает много памяти. Во-вторых, очистить кэш памяти linux может понадобиться, если вы изменяли какие-либо настройки файловой системы или ядра, а теперь хотите проверить как это отразилось на скорости операций чтения/записи. В таком случае можно очистить все кэши и сделать это без перезагрузки, что очень удобно.

Операционная система Linux разработана таким образом, что перед тем как обратиться к диску, будет просмотрен кэш диска, и если там есть нужные данные, к диску обращений не будет. Если очистить кэш Linux то операционная система будет работать немного медленнее, поскольку ей придется искать данные на диске.

Автоматическая очистка кэша

Давайте рассмотрим как автоматически очистить кэш памяти ежедневно в два часа ночи с помощью планировщика заданий cron.

Сначала создадим bash скрипт со следующим содержимым:

sudo vi /usr/local/bin/clearcache.sh

!/bin/bash
sync ; echo 1 > /proc/sys/vm/drop_caches

Очищать будем только страничный кэш, так как он занимает больше всего. Другие виды трогать не будем, чтобы зря не понижать производительность системы.

Дальше сделайте скрипт исполняемым:

sudo chmod 755 /usr/local/bin/clearcache.sh

Осталось добавить задание в планировщик cron. Для этого выполните команду:

И в открывшемся редакторе добавьте строчку:

0 2 * * * /usr/local/bin/clearcache.sh

Теперь этот скрипт будет выполняться каждую ночь и выполнять очистку памяти, чтобы сервер мог работать нормально.

Настройка размера кэша памяти

Куда удобнее не очищать кэш каждый раз, а настроить ограничение, при превышении которого система сама будет удалять лишние страницы. Вы не можете явно ограничить сколько мегабайт может система использовать под кэш. Будет использоваться вся доступная память по мере необходимости, но можно настроить скорость удаления просроченных страниц из кэша.

За это отвечает файл /proc/sys/vm/vfs_cache_pressure. Он содержит относительный показатель, насколько агрессивно нужно удалять страницы из кэша. По умолчанию установлен параметр 100. Если его уменьшить ядро будет реже удалять страницы и это приведет к очень быстрому увеличению кэша. При нуле страницы вообще не будут удаляться. Если значение больше 100, размер кэша будет увеличиваться медленнее и неиспользуемые страницы будут сразу удаляться.

Например, сделаем минимальный размер кэша:

echo 1000 > /proc/sys/vm/vfs_cache_pressure

Не забудьте, что это очень сильно снизит производительность вашей системы, потому что вместо кэша данные будут читаться из диска.

Как очистить память подкачки

Пространство подкачки очистить очень просто. Для этого выполните:

swapoff -a && swapon -a

Имейте в виду, что при очистке swap, все данные будут перенесены обратно в оперативную память.

Как освободить память занимаемую процессами

Если в вашей системе нет памяти и кэш здесь ни при чём, следует завершить несколько процессов, потребляющих больше всего памяти. Для этого сначала надо вычислить такие процессы. Чтобы это сделать можно воспользоваться утилитой ps:

ps -e -o pid,user,%mem,command —sort %mem

Как видите, больше всего здесь памяти занимает chromium. Теперь вам надо его завершить. Идентификатор процесса, по которому его можно завершить отображается в первой колонке. Поэтому:

Более подробно о том как завершить процесс читайте в этой статье. Таким образом, вы можете освободить память от процессов, которые занимают больше всего памяти, а потом уже настроить zram или swap для того, чтобы память не переполнялась.

Выводы

Вот и все. Вы уже знаете очистить кэш linux и освободить память. Не забудьте, что все команды, приведенные в этой статье нужно выполнять от имени суперпользователя, иначе ничего работать не будет. Если остались вопросы, спрашивайте в комментариях!

Источник

Оцените статью