Linux удалить файлы старше чем

Delete files older than 10 days using shell script in Unix [duplicate]

And take care that ./my_dir exists to avoid bad surprises !

find /home/scripts/*.script -mtime +10 type f -delete will be ok for delete these? 2012.11.21.09_33_52.script 2012.11.21.09_33_56.script 2012.11.21.09_33_59.script

It depends of the date of the modification, like what ls -l displays. Are the date the same as ls -l ? But a simple test will tell you =)

Be VERY careful to supply an absolute path on commands like these! Once, using a command very much like this in a cron job, I accidentally deleted every file on my production mail server older than 10 days, which I can tell you was no fun to recover from.

@DSimon Thanks for sharing your horror story to help us avoid our own! I had a few directories to do this to, so inspired by your comment, inside my for a in . loop, I added a if [ -d $a ]; then. to my script!

Just spicing up the shell script above to delete older files but with logging and calculation of elapsed time

#!/bin/bash path="/data/backuplog/" timestamp=$(date +%Y%m%d_%H%M%S) filename=log_$timestamp.txt log=$path$filename days=7 START_TIME=$(date +%s) find $path -maxdepth 1 -name "*.txt" -type f -mtime +$days -print -delete >> $log echo "Backup:: Script Start -- $(date +%Y%m%d_%H%M)" >> $log . code for backup . or any other operation . >> $log END_TIME=$(date +%s) ELAPSED_TIME=$(( $END_TIME - $START_TIME )) echo "Backup :: Script End -- $(date +%Y%m%d_%H%M)" >> $log echo "Elapsed Time :: $(date -d 00:00:$ELAPSED_TIME +%Hh:%Mm:%Ss) " >> $log 

The code adds a few things.

  • log files named with a timestamp
  • log folder specified
  • find looks for *.txt files only in the log folder
  • type f ensures you only deletes files
  • maxdepth 1 ensures you dont enter subfolders
  • log files older than 7 days are deleted ( assuming this is for a backup log)
  • notes the start / end time
  • calculates the elapsed time for the backup operation.

Note: to test the code, just use -print instead of -print -delete. But do check your path carefully though.

Note: Do ensure your server time is set correctly via date — setup timezone/ntp correctly . Additionally check file times with ‘stat filename’

Note: mtime can be replaced with mmin for better control as mtime discards all fractions (older than 2 days (+2 days) actually means 3 days ) when it deals with getting the timestamps of files in the context of days

-mtime +$days ---> -mmin +$((60*24*$days)) 

Источник

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

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

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

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

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

Читайте также:  Linux copy changed files only

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

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.

Источник

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.

Читайте также:  Обновить кэш шрифтов линукс

Источник

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.

Читайте также:  Linux отобразить запущенные процессы

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:

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.

Источник

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