Linux remove old file

Delete Files Older Than One year on Linux

By the time, many files are still on my system and I don’t need them anymore, so how to delete all files that are one year old at least?

1 Answer 1

You can do it with this command

find /path/to/files* -mtime +365 -exec rm <> \; 

/path/to/files* is the path to the files.

-mtime is used to specify the number of days old that the file is. +365 will find files older than 365 days which is one year

-exec allows you to pass in a command such as rm.

Edit Thanks to @Oli note —> you can do it by:

find /path/to/files* -mtime +365 -delete 

You should always quote the <> in -exec (so it reads -exec rm «<>» \; ). This makes sure that spaces are handled properly. And you could just use the -delete function instead of -exec .

@Oli Huh. (What you have said cannot be right, considering that the shell turns «<>» into <> before passing it to find in the first place; then find substitutes for it. Quoting <> is suggested in case < and >themselves may sometimes be treated specially by the shell—which has nothing to do with blank spaces. And often <> doesn’t have to be quoted. I can’t think of any situation, at least when invoking find from a Bourne-style shell, when <> , with nothing inside, appearing by itself as an argument, would have to be quoted. Can you?)

@EliahKagan Yeah, turns out find handles escaping for itself but it’s not a bad habit to be in while scripting. It doesn’t hurt.

@Oli But it doesn’t help, even in principle. If find didn’t handle escaping, «<>» would still have the same effect as <> —just neither would work, instead of both working. That <> and «<>» behave the same isn’t—and cannot be—due to any special feature of find. Confusing what gets expanded by the shell with what gets expanded by some other program is a bad habit. We all make that mistake occasionally, but it’s still a mistake—not a best practice. (One might still quote <> to help humans see it’s not a pattern for brace expansion, but that’s unrelated to word splitting.)

Читайте также:  Openvpn gui client linux

Источник

Удаление файлов старше n дней в Linux

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

По ходу данной статьи мы разберемся с удалением файлов старше определенного количества дней в Ubuntu. Заодно объясним некоторые нюансы этой процедуры.

Удаление файлов старше n дней в Linux

Для терминала Ubuntu существует специальная команда find, которая отвечает за поиск файлов на компьютере. А с помощью опции -mtime получится найти только те файлы, дата изменения которых старше заданного временного промежутка. В качестве примера возьмем каталог Downloads и срок в 35 дней.

Откройте терминал и запустите следующую команду:

find ~/Downloads -type f -mtime +35

8fsAGtAO1XbSkAAAAASUVORK5CYII=

Вам необязательно действовать напрямую и стирать сразу же все файлы. Их можно отсортировать дополнительно по еще одному признаку, например, по названию или расширению. Для этого есть опция -name, которая прописывается сразу же после директории. Если нужно избавиться только от zip-архивов, то подойдет такая команда:

find ~/Downloads -name «*.zip» -type f -mtime +35 -delete

ByZkw8E2C2n2AAAAAElFTkSuQmCC

Ну и напоследок хотелось бы упомянуть, что при запуске терминала Ubuntu из конкретной папки вручную директорию прописывать не придется. Это можно сделать через стандартное приложение Файлы, если перейти к нужному каталогу, кликнуть правой клавишей мыши по пустому месту и в контекстном меню выбрать пункт Открыть в терминале.

7v5wAAAABJRU5ErkJggg==

Тогда команда для поиска, если она еще нужна, сократится до следующего варианта:

wd2Gmddp20QPQAAAABJRU5ErkJggg==

А для удаления не забудьте в конце дописать опцию -delete:

8f507C0nZQ++gAAAAASUVORK5CYII=

Выводы

По ходу данной статьи мы вкратце объяснили, как можно в конкретном каталоге отыскать файлы старше определенного возраста через терминал Ubuntu, а также как удалить файлы старше n дней linux. Сама по себе процедура довольно простая, но может сэкономить много времени при чистке уже ненужных данных с компьютера.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to Delete Files Older than 30 days in Linux

Regularly cleaning out old unused files from your server is the best practice. For example, if we are running a daily/hourly backup of files or databases on the server then there will be much junk created on the server. So clean it regularly. To do it you can find older files from the backup directory and clean them.

Читайте также:  Изменить default route linux

This article describes you to how to find and delete files older than 30 days. Here 30 days older means the last modification date is before 30 days.

1. Delete Files older Than 30 Days

Using the find command, you can search for and delete all files that have been modified more than X days. Also, if required you can delete them with a single command.

First of all, list all files older than 30 days under /opt/backup directory.

find /opt/backup -type f -mtime +30 

Verify the file list and make sure no useful file is listed in the above command. Once confirmed, you are good to go to delete those files with the following command.

find /opt/backup -type f -mtime +30 -delete 

2. Delete Files with Specific Extension

You can also specify more filters to locate commands rather than deleting all files. For example, you can only delete files with the “.log” extension and modified before 30 days.

For the safe side, first, do a dry run and list files matching the criteria.

find /var/log -name "*.log" -type f -mtime +30 

Once the list is verified, delete those files by running the following command:

find /var/log -name "*.log" -type f -mtime +30 -delete 

The above command will delete only files with a .log extension and with the last modification date older than 30 days.

3. Delete Old Directory Recursively

The -delete option may fail if the directory is not empty. In that case, we will use the Linux rm command with find to accomplish the deletion.

Searching all the directories under /var/log modified before 90 days using the command below.

find /var/log -type d -mtime +90 

Here we can execute the rm command using -exec command line option. Find command output will be sent to rm command as input.

find /var/log -type d -mtime +30 -exec rm -rf <> \; 

WARNING: Before removing the directory, Make sure no user directory is being deleted. Sometimes parent directory modification dates can be older than child directories. In that case, recursive delete can remove the child directory as well.

Conclusion

You have learned how to find and delete files in the Linux command line that have been modified more than a specified number of days ago. That will help you clean up your system from unwanted files.

Источник

find files older than X days in bash and delete

I have a directory with a few TB of files. I’d like to delete every file in it that is older than 14 days. I thought I would use find . -mtime +13 -delete . To make sure the command works as expected I ran find . -mtime +13 -exec /bin/ls -lh ‘<>‘ \; | grep ‘‘ . The latter should return nothing, since files that were created/modified today should not be found by find using -mtime +13 . To my surprise, however, find just spew out a list of all the files modified/created today!

Читайте также:  Astra linux сколько занимает места

See -daystart option for find. Your find counts exactly 24*13 hours backwards, leaving files which might be 24*13 — 1 minute and later your another find will find those.

Just figured it out! The reason is ls . find finds a directory with mtime +13 and ls simply list all it’s content no matter what mtime the files have (facepalm!).

Always test your find command first by replacing «-delete» with «-print». It may also include the current directory (.) in the result list, which may or may not be what you want.

3 Answers 3

find your/folder -type f -mtime +13 -exec rm <> \; 

Doesn’t work for filenames containing spaces. Either (GNU specific) find -delete or find -print0 | xargs -0 rm

@grebneke: can you back up your statement with examples or facts? find ‘s <> is well-known to be safe regarding spaces and funny symbols in file names.

$ find ./folder_name/* -type f -mtime +13 -print | xargs rm -rf 

The -r switch is useless. Moreover, you’ll run into problems if you have filenames containing spaces or other funny symbols. Use -print0 and xargs -0 . if your utilities support them, otherwise, use @Mindx’s answer. Or, if your find supports it, use the -delete test of find as so: find ./folder_name -type f -mtime +13 -delete .

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

using asterisk find ./folder_name/* is mistake, because shell will expand ‘‘ info all items existent in this folder. When folder keeps extremally huge items (files or directories), it will exceed maximum arguments or max characters for execute command. Better remove ‘‘ signt, this will do the same, without any automated shel expand. but if you need to find specified names, use option -name ‘some*thing’ and give expansion directly to find internals.

Источник

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