Linux удаление папки старше

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.

Источник

bash как удалить файлы и директории, старше x-дней?

Есть некая директория Test. В ней находятся файлы и папки. Как удалить только то, что старше 10 дней к примеру.

find /volume1/Test -cmin +$storetime -delete 

приводит к удалению и самой директории Test, если в ней нет свежих файлов, естественно.

find /volume1/Test -mtime +10 -exec rm <> \; ?

Читайте также:  Установка python alt linux

TС: добавь ключик type -f к файнду и в результате будут только файлі.

TС: добавь ключик type -f к файнду и в результате будут только файлі.

Там не только файлы под удаление, но и папки, в том то и проблема.

Illujanka ( 07.11.19 10:21:52 MSK )
Последнее исправление: Illujanka 07.11.19 10:26:37 MSK (всего исправлений: 1)

find /volume1/Test -mtime +10 -exec rm <> \; ? 

При Test, без свежих файлов, удаляет и саму Test

Illujanka ( 07.11.19 10:23:13 MSK )
Последнее исправление: Illujanka 07.11.19 10:25:49 MSK (всего исправлений: 1)

Разница в скорости будет незаметна, но зато есть везде, ибо posix. Но для не \;, а +

vodz ★★★★★ ( 07.11.19 10:27:24 MSK )
Последнее исправление: vodz 07.11.19 10:28:39 MSK (всего исправлений: 1)

про ключ -mindepth тебе уже писали

про ключ -mindepth тебе уже писали

Всегда удивляет в тутошних комментаторов желание решить как можно узкую задачу с возможностью появления завтра у ТСа еще вопроса, например, что делать, если в каталоге появится другие подкаталоги и rm на них ругается. Одно дело, когда универсальное требует кучу нового кода, другое дело, что правильный ответ скорее всего не -mindepth, а таки тоже уже данный «-type f»

vodz ★★★★★ ( 07.11.19 11:12:42 MSK )
Последнее исправление: vodz 07.11.19 11:14:44 MSK (всего исправлений: 1)

При Test, без свежих файлов, удаляет и саму Test

Вариант с * не затронет сам каталог

Источник

Удаление папок старше N месяцев

Нужно удалять то, что старше 3-х месяцев (с затиранием пустых каталогов). Есть ли какой-то простой метод Спасибо.

find /path/to/dir* -type f -mtime +90 -delete

удалит только пустые директории

не совсем 3 месяца, но не меньше. зато максимально просто

rm -rf /home/share/*/$(date -d '4 months ago' '+%Y/%m') 

futurama ★★★★★ ( 05.09.19 15:13:41 MSK )
Последнее исправление: futurama 05.09.19 15:14:45 MSK (всего исправлений: 2)

rmdir —ignore-fail-on-non-empty —parents /path/to/directory

если точнее, лень было просто писать.

find /your/path -mtime +90 -delete find /your/path -d -empty -delete

Avial ★★★★★ ( 05.09.19 15:45:13 MSK )
Последнее исправление: Avial 05.09.19 15:45:53 MSK (всего исправлений: 2)

find /your/path -mtime +90 -delete — Это на сколько я понял удалит не только файлы но и папки созданные до этой даты. Соответственно нужно добавить -type f, как посоветовали выше

в случае, если эти директории будут пустые и старше 90 и с директории с файлами тоже — если все файлы в директории старше 90 дней. в противном случае, если будет хоть один файл младше — удалит все файлы старше и выдаст ошибку при попытке удаления директории, так как она непуста.

второй поубивает просто все пустые директории

Источник

Как найти и удалить файлы старше конкретной даты в Linux

Как найти и удалить файлы старше конкретной даты в Linux

Хочу в этой теме «Как найти и удалить файлы старше конкретной даты в Linux» рассказать как можно найти и удалить определенные файлы по дате в ОС Linux таких как Debian, Ubuntu или Redhat, Centos. На готовых примера покажу что и как нужно делать.

Читайте также:  Установка драйвера nvidia arch linux

1. Посмотрим список всех файлов в папке с датой изменения, для этого стоит выполнить команду:

пример использование команды ls -lah для вывода подробной информации о файлах

пример использование команды ls -lah для вывода подробной информации о файлах

2. Чтобы узнать сегодняшнюю дату, нужно выполнить:

# date on Jul 14 04:04:52 EEST 2014

3. Команда что выше не вывела полную дату, можно это исправить:

# ls --full-time total 36576 drwxr-xr-x 8 root root 4096 2014-06-06 07:16:21.000000000 +0300 firefox -rw-r--r-- 1 root staff 37445961 2014-06-06 07:21:16.000000000 +0300 firefox-30.0.tar.bz2

4. Допустим нужно найти файлы и удалить их по определенной дате.

Если нужно найти все файлы свыше 3 дня и после чего удалить их:

# find /home/captain -type f -mtime +3 -exec rm -rf <> \;

Если нужно найти все файлы свыше 90 дней и после чего удалить их:

# find /home/captain -type f -mtime +90 -exec rm -rf <> \;

Если нужно найти все файлы свыше 365 дней и после чего удалить их:

# find /home/captain -type f -mtime +365 -exec rm -rf <> \;

Если нужно найти все файлы свыше 100 дней и после чего удалить их:

# find /home/captain -type f -mtime +100 -exec rm -rf <> \;

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

$ find /dir/ -atime +N | xargs rm -f
$ find /dir/ -name "*.jpg" -mtime +N -exec rm -f <> \;

Ключи:
-name — искать по имени файла, при использовании подстановочных образцов параметр заключается в кавычки.
-type — тип искомого: f=файл, d=каталог, l=ссылка (link).
-user — владелец: имя пользователя или UID.
-group — владелец: группа пользователя или GID.
-perm — указываются права доступа.
-size — размер: указывается в 512-байтных блоках или байтах (признак байтов — символ «c» за числом).
-atime — время последнего обращения к файлу.
-ctime — время последнего изменения владельца или прав доступа к файлу.
-mtime — время последнего изменения файла.
-newer другой_файл — искать файлы созданные позже, чем другой_файл.
-delete — удалять найденные файлы.
-ls — генерирует вывод как команда ls -dgils.
-print — показывает на экране найденные файлы.
-exec command <> \; — выполняет над найденным файлом указанную команду; обратите внимание на синтаксис.
-ok — перед выполнением команды указанной в -exec, выдаёт запрос.
-depth — начинать поиск с самых глубоких уровней вложенности, а не с корня каталога.
-prune — используется, когда вы хотите исключить из поиска определённые каталоги.
N — количество дней.

Читайте также:  Linux скопировать файл другой сервер

Источник

Shell script to delete directories older than n days

To they bare any relation on their actual creation/modification time? Because find could do it without looking at the name then.

What do you mean by «older than»? Are you referring to the time the directory was created, the time its contents were last changed, or something else? Be careful with some of the answers below; ctime is the inode change time. For a directory, it changes when files are added or removed from the directory.

5 Answers 5

This will do it recursively for you:

find /path/to/base/dir/* -type d -ctime +10 -exec rm -rf <> \; 

Explanation:

  • find : the unix command for finding files / directories / links etc.
  • /path/to/base/dir : the directory to start your search in.
  • -type d : only find directories
  • -ctime +10 : only consider the ones with modification time older than 10 days
  • -exec . \; : for each such result found, do the following command in .
  • rm -rf <> : recursively force remove the directory; the <> part is where the find result gets substituted into from the previous part.

Alternatively, use:

find /path/to/base/dir/* -type d -ctime +10 | xargs rm -rf 

Which is a bit more efficient, because it amounts to:

rm -rf dir1; rm -rf dir2; rm -rf dir3; . 

With modern versions of find , you can replace the ; with + and it will do the equivalent of the xargs call for you, passing as many files as will fit on each exec system call:

find . -type d -ctime +10 -exec rm -rf <> + 

-mtime was better for me as it checks content changes rather than permission changes, otherwise this was perfect.

The more efficient approach can backfire if you have too many folders to delete: stackoverflow.com/questions/11289551/…. For the same reason, in order to avoid deletion of the base folder it’s better to use -mindepth 1 (rather than /path/to/folder/* ).

If you want to delete all subdirectories under /path/to/base , for example

/path/to/base/dir1 /path/to/base/dir2 /path/to/base/dir3 

but you don’t want to delete the root /path/to/base , you have to add -mindepth 1 and -maxdepth 1 options, which will access only the subdirectories under /path/to/base

-mindepth 1 excludes the root /path/to/base from the matches.

-maxdepth 1 will ONLY match subdirectories immediately under /path/to/base such as /path/to/base/dir1 , /path/to/base/dir2 and /path/to/base/dir3 but it will not list subdirectories of these in a recursive manner. So these example subdirectories will not be listed:

/path/to/base/dir1/dir1 /path/to/base/dir2/dir1 /path/to/base/dir3/dir1 

So , to delete all the sub-directories under /path/to/base which are older than 10 days;

find /path/to/base -mindepth 1 -maxdepth 1 -type d -ctime +10 | xargs rm -rf 

Источник

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