Linux find delete mtime

How to delete files older than X hours

This will delete of the files older than 1 day. However, what if I need a finer resolution that 1 day, say like 6 hours old? Is there a nice clean way to do it, like there is using find and -mtime?

9 Answers 9

Does your find have the -mmin option? That can let you test the number of mins since last modification:

find $LOCATION -name $REQUIRED_FILES -type f -mmin +360 -delete 

Or maybe look at using tmpwatch to do the same job. phjr also recommended tmpreaper in the comments.

Using —mmin +X returns all files with my find. My fault for not checking this first, but this command just deleted most of my home directory. For me, —mmin -X is the correct argument.

tmpreaper is a fork of tmpwatch. It is safer, and exists as a debian package in the distro. Benefits over find -delete : tmpreaper will not remove symlinks, sockets, fifos, or special files

Point out that $REQUIRED_FILES need to be in quotes (double quotes) and you can use a pattern like: «.txt» for all .txt files or files beginning with a pattern like: «temp-» to delete all files named with temp-

@PaulDixon how to modify this so that $LOCATION and $REQUIRED_FILES can both have multiple values such as dir1 dir2 and *.txt *.tmp ?

@Enissay $LOCATION is a single directory. For multiple extensions you’d probably want to use a pattern with -regex — see stackoverflow.com/questions/5249779/…

Here is the approach that worked for me (and I don’t see it being used above)

$ find /path/to/the/folder -name '*.*' -mmin +59 -delete > /dev/null 

deleting all the files older than 59 minutes while leaving the folders intact.

Better to single-quote ‘*.*’ or the shell will expand it to actual filenames instead of keeping it as a wildcard for find to resolve. This breaks find ‘s recursive operation on subdirs.

Also keep in mind that -name ‘*.*’ will not delete files that have no extension, such as README , Makefile , etc.

You could to this trick: create a file 1 hour ago, and use the -newer file argument.

(Or use touch -t to create such a file).

there is no -older switch (at least in my find command), and that’s what would be needed. -newer doesn’t help.

can you give a touch command that would generate a file 1 hour old that will work on machines that can’t use -mmin? (If you’re on Linux, -mmin is available, if not then date and other commands are also feeble in comparison.)

@iconoclast touch -t $(date -d ‘-1 hour’ +%Y%m%d%H%M.00) test Creates file test that’s always 1 hour old.

To rm files and directories older than file.ext run rm -r `find -maxdepth 1 -not -newer file.ext` . To rm files and directories newer than file.ext do rm -r `find -maxdepth 1 -newer file.ext` . To place file.ext where you want it in time run touch -t $(date -d ‘-1 hour’ +%Y%m%d%H%M.00) file.ext where ‘-1 hour’ specifies «1 hour ago». Credit: xoftl, rovr138, nickf.

 Example 6 Selecting a File Using 24-hour Mode The descriptions of -atime, -ctime, and -mtime use the ter- minology n ``24-hour periods''. For example, a file accessed at 23:59 is selected by: example% find . -atime -1 -print at 00:01 the next day (less than 24 hours later, not more than one day ago). The midnight boundary between days has no effect on the 24-hour calculation. 

If you do not have «-mmin» in your version of «find», then «-mtime -0.041667» gets pretty close to «within the last hour», so in your case, use:

Читайте также:  Add group command in linux

so, if X means 6 hours, then:

works because 24 hours * 0.25 = 6 hours

Was hopeful because this old UNIX doesn’t have -mmin, but, sadly this is of no help as this old UNIX also does not like fractional values for mtime: find: argument to -mtime must be an integer in the range -2147483647 to 2147483647

If one’s find does not have -mmin and if one also is stuck with a find that accepts only integer values for -mtime , then all is not necessarily lost if one considers that «older than» is similar to «not newer than».

If we were able to create a file that that has an mtime of our cut-off time, we can ask find to locate the files that are «not newer than» our reference file.

To create a file that has the correct time stamp is a bit involved because a system that doesn’t have an adequate find probably also has a less-than-capable date command that could do things like: date +%Y%m%d%H%M%S -d «6 hours ago» .

Fortunately, other old tools can manage this, albeit in a more unwieldy way.

To begin finding a way to delete files that are over six hours old, we first have to find the time that is six hours ago. Consider that six hours is 21600 seconds:

$ date && perl -e '@d=localtime time()-21600; \ printf "%4d%02d%02d%02d%02d.%02d\n", $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]' > Thu Apr 16 04:50:57 CDT 2020 202004152250.57 

Since the perl statement produces the date/time information we need, use it to create a reference file that is exactly six hours old:

$ date && touch -t `perl -e '@d=localtime time()-21600; \ printf "%4d%02d%02d%02d%02d.%02d\n", \ $d[5]+1900,$d[4]+1,$d[3],$d[2],$d[1],$d[0]'` ref_file && ls -l ref_file Thu Apr 16 04:53:54 CDT 2020 -rw-rw-rw- 1 root sys 0 Apr 15 22:53 ref_file 

Now that we have a reference file exactly six hours old, the «old UNIX» solution for «delete all files older than six hours» becomes something along the lines of:

$ find . -type f ! -newer ref_file -a ! -name ref_file -exec rm -f "<>" \; 

It might also be a good idea to clean up our reference file.

Источник

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.

Читайте также:  Simple linux or ubuntu

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.

Источник

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

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

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

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

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

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

find ~/Downloads -type f -mtime +35

Читайте также:  Linux curl put file

8fsAGtAO1XbSkAAAAASUVORK5CYII=

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

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

ByZkw8E2C2n2AAAAAElFTkSuQmCC

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

7v5wAAAABJRU5ErkJggg==

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

wd2Gmddp20QPQAAAABJRU5ErkJggg==

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

8f507C0nZQ++gAAAAASUVORK5CYII=

Выводы

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

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

Источник

Delete files older than X days +

Possibly fun when I have files with spaces. E.g a file called «test one» and rm gets fed rm test one . (Which will delete a file called «test» and a file called «one», but not a file called «test one»). Hint: -delete or -print0

As a side note, always quote the argument provided by find to avoid issues with special characters, as mentioned in the answer’s first line. E.g.: find /path/to/files/ -exec somecommand ‘<>‘ \;

4 Answers 4

Be careful with special file names (spaces, quotes) when piping to rm.

There is a safe alternative — the -delete option:

find /path/to/directory/ -mindepth 1 -mtime +5 -delete 

That’s it, no separate rm call and you don’t need to worry about file names.

Replace -delete with -depth -print to test this command before you run it ( -delete implies -depth ).

  • -mindepth 1 : without this, . (the directory itself) might also match and therefore get deleted.
  • -mtime +5 : process files whose data was last modified 5*24 hours ago.

Alternatively, if you want to do the same for all files NEWER than five days: find /path/to/directory/ -mindepth 1 -mtime -5 -delete

Note that every find argument is a filter that uses the result of the previous filter as input. So make sure you add the -delete as the last argument. IE: find . -delete -mtime +5 will delete EVERYTHING in the current path.

Note that this command will not work when it finds too many files. It will yield an error like:

bash: /usr/bin/find: Argument list too long 

Meaning the exec system call’s limit on the length of a command line was exceeded. Instead of executing rm that way it’s a lot more efficient to use xargs. Here’s an example that works:

find /root/Maildir/ -mindepth 1 -type f -mtime +14 | xargs rm 

This will remove all files (type f) modified longer than 14 days ago under /root/Maildir/ recursively from there and deeper (mindepth 1). See the find manual for more options.

Источник

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