Скрипты 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 

Источник

Читайте также:  Modbus rtu client linux

How to delete a file in bash

Any file can be deleted temporarily and permanently in bash. When a file is removed temporarily by using a graphical user interface, then it is stored in the Trash folder, and it can be restored if required. The file which is removed permanently cannot be restored later normally. `rm` command is used to remove the file permanently from the computer. If any file is removed accidentally by this command, then it can be restored from the backup. How any file can be removed from the terminal and the graphical user interface are shown in this article.

Delete the file using `rm` command:

`rm` command can be used with option and without the option for the different types of delete. The syntax of the `rm` command is given below.

Syntax:

‘-i’ option can be used with `rm` command to provide a prompt before deleting any file to prevent accidental deletion. ‘-f’ option can be used with `rm` command to remove any file forcefully. The different uses of the `rm` command are shown below.

Example-1: Delete the file using `rm` command without the option

You can apply the ‘rm’ command to remove an existing file. In the following script, an empty file is created by using the ‘touch’ command to test ‘rm‘ command. Next, ‘rm’ command is used to remove the file, test.txt.

# Set the filename
filename = ‘test.txt’
# Create an empty file
touch $filename
# Check the file is exists or not
if [ -f $filename ] ; then
rm test.txt
echo » $filename is removed»
fi

Example-2: Delete the file using `rm` command with -i option

The following script will ask for permission from the user before removing the file for ‘-i’ option. Here, the filename will be taken from the user as input. If the file exists and the user press ‘n’ then the file will not remove otherwise the file will remove.

# Take the filename
read -p ‘Enter the filename to delete: ‘ filename

# Check the file is exists or not
if [ -f $filename ] ; then
# Remove the file with permission
rm -i » $filename »
# Check the file is removed or not
if [ -f $filename ] ; then
echo » $filename is not removed»
else
echo » $filename is removed»
fi
else
echo «File does not exist»
fi

Example-3: Delete the file using `rm` command with -v option

The following script will take the filename by a command-line argument. If the file exists then, it will print a remove message with the filename for ‘-v’ option.

# Check the file is exists or not
if [ [ $1 ! = «» && -f $1 ] ] ; then
# Print remove message
rm -v $1
else
echo «Filename is not provided or filename does not exist»
fi

Example-4: Delete multiple files using `rm` command

More than one file can be deleted by using ‘rm’ command and separating the filenames with space. In the following script, multiple filenames will be taken from the command line arguments. If any file does not exist, then it will show a message otherwise filenames will be combined by the space and stored into the variable named ‘files’. Next, the rm command will be executed with the ‘files’ variable to remove multiple files.

Читайте также:  Linux file with dot

# Check the multiple filenames are given or not
if [ $# > 2 ] ; then
# Reading argument values using loop
for argval in «$@»
do
if [ -f $argval ] ; then
files+= $argval $space
else
echo » $argval does not exist»
fi
done

# Remove files
rm $files
echo «files are removed.»
else
echo «Filenames are not provided, or filename does not exist»
fi

Conclusion:

The above examples show the different types of ways to delete the file using a bash script to help bash users to do this type of task easily.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.

Источник

Удаление файлов старше 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. Сама по себе процедура довольно простая, но может сэкономить много времени при чистке уже ненужных данных с компьютера.

Читайте также:  Linux local bin directory

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

Источник

How to remove files and directories quickly via terminal (bash shell) [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.

This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.

From a terminal window: When I use the rm command it can only remove files.
When I use the rmdir command it only removes empty folders. If I have a directory nested with files and folders within folders with files and so on, is there a way to delete all the files and folders without all the strenuous command typing? If it makes a difference, I am using the Mac Bash shell from a terminal, not Microsoft DOS or Linux.

Just in case you wish to restore the files in future , don’t use «rm» for such cases . Use «rm-trash» : github.com/nateshmbhat/rm-trash

4 Answers 4

-r «recursive» -f «force» (suppress confirmation messages)

+1 and glad you added the «Be careful!» part. definitely a «Sawzall» command that can quickly turn a good day into a bad one.. if wielded carelessly.

@itsmatt: You know what they say. give someone a Sawzall, and suddenly every problem looks like hours of fun!

On a Mac? Do this instead: brew install trash then trash -rf some_dir This will move the unwanted directory into your trashbin instead of just vanishing Prestige-style into the ether. (source)

Would remove everything (folders & files) in the current directory.

But be careful! Only execute this command if you are absolutely sure, that you are in the right directory.

Yes, there is. The -r option tells rm to be recursive, and remove the entire file hierarchy rooted at its arguments; in other words, if given a directory, it will remove all of its contents and then perform what is effectively an rmdir .

The other two options you should know are -i and -f . -i stands for interactive; it makes rm prompt you before deleting each and every file. -f stands for force; it goes ahead and deletes everything without asking. -i is safer, but -f is faster; only use it if you’re absolutely sure you’re deleting the right thing. You can specify these with -r or not; it’s an independent setting.

And as usual, you can combine switches: rm -r -i is just rm -ri , and rm -r -f is rm -rf .

Also note that what you’re learning applies to bash on every Unix OS: OS X, Linux, FreeBSD, etc. In fact, rm ‘s syntax is the same in pretty much every shell on every Unix OS. OS X, under the hood, is really a BSD Unix system.

Источник

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