Linux скрипт удалить файлы

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.

Источник

doctor Brain

В GNU/Linux операционных системах любые объекты являются файлами, манипуляции с файлами — очень мощный и востребованный инструмент.

С точки зрения bash, как и с точки зрения людей, все объекты файловой системы делятся на каталоги и файлы.

В этой небольшой заметке мы изучим как проверить: существует ли файл, является ли файл пустым, как удалить файл в bash.

Как проверить файл на наличие?

Во всех случаях мы используем команду test . Аналогами команды test являются конструкции с одинарными и двойными квадратными скобками [. ] или [[. ]] .

Параметр -e позволяет проверить объект на наличие, независимо от того чем он является: каталогом или файлом.

if [[ -e /home ]] then echo "Каталог существует" fi 

Является ли объект файлом можно узнать с помощью параметра -f . В данном случае мы используем логический оператор отрицания ! :

if [[ ! -f /tmp/file.txt ]] then echo "Файл не найден" fi 

Является ли файл пустым?

Чтобы узнать является ли файл пустым, нужен параметр -s . Проверка на наличие данных особенно важна, если файл помечен на удаление:

if [[ -s /tmp/file.txt ]] then echo "Файл содержит данные" fi 

Как удалить файл

Чтобы удалить один файл, достаточно использовать команду rm :

Новые публикации

Photo by CHUTTERSNAP on Unsplash

JavaScript: сохраняем страницу в pdf

HTML: Полезные примеры

CSS: Ускоряем загрузку страницы

JavaScript: 5 странностей

JavaScript: конструктор сортировщиков

Категории

О нас

Frontend & Backend. Статьи, обзоры, заметки, код, уроки.

© 2021 dr.Brain .
мир глазами веб-разработчика

Источник

Скрипт на удаление файлов

Надо написать скрипт на shell , имеющий два входных параметра: имя каталога и набор символов.
Скрипт выполняет такие действия:
1) вывод на экран перечня файлов, «дочерних» к заданному каталогу, которые имеют в своем имени заданный набор символов;
2) уничтожение всех остальных файлов заданного каталога;

direct=$1 files=$2 echo "Найденные файлы: " find $direct/* -name \*$files* | cat ; find $direct/* ! -name \*$files* > file ;

В последней строке в файл записываются адреса тех файлов которые не подходят. Мне необходимо удалить неподходящие файлы при помощи команы rm. Использовать в find -delete нельзя. Чет я туплю как пройтись по файлу с абсолютными именами и удалить эти файлы при помощи rm

Читайте также:  Check disk health in linux

Добавлено через 52 минуты

direct=$1 ; files=$2 ; echo "Найденные файлы: " ; find $direct/* -name \*$files* | cat ; rm -i -r `find $direct/* -maxdepth 0 ! -name \*$files*` ;

Источник

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.

Читайте также:  Поиск через командную строку linux

# 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.

# 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.

Источник

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