Bash linux delete file

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 .

Читайте также:  Несколько linux на одном диске

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.

Источник

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.

Читайте также:  Copy all files in linux terminal

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

Источник

Use rm to Delete Files and Directories on Linux

Estamos traduciendo nuestros guías y tutoriales al Español. Es posible que usted esté viendo una traducción generada automáticamente. Estamos trabajando con traductores profesionales para verificar las traducciones de nuestro sitio web. Este proyecto es un trabajo en curso.

This guide shows how to use rm to remove files, directories, and other content from the command line in Linux.

To avoid creating examples that might remove important files, this Quick Answer uses variations of filename.txt . Adjust each command as needed.

The Basics of Using rm to Delete a File

rm filename1.txt filename2.txt 

Options Available for rm

-i Interactive mode

Confirm each file before delete:

-f Force

-v Verbose

Show report of each file removed:

-d Directory

Note: This option only works if the directory is empty. To remove non-empty directories and the files within them, use the r flag.

-r Recursive

Remove a directory and any contents within it:

Combine Options

Options can be combined. For example, to remove all .png files with a prompt before each deletion and a report following each:

remove filename01.png? y filename01.png remove filename02.png? y filename02.png remove filename03.png? y filename03.png remove filename04.png? y filename04.png remove filename05.png? y filename05.png

-rf Remove Files and Directories, Even if Not Empty

Add the f flag to a recursive rm command to skip all confirmation prompts:

Combine rm with Other Commands

Remove Old Files Using find and rm

Combine the find command’s -exec option with rm to find and remove all files older than 28 days old. The files that match are printed on the screen ( -print ):

find filename* -type f -mtime +28 -exec rm '<>' ';' -print 

In this command’s syntax, <> is replaced by the find command with all files that it finds, and ; tells find that the command sequence invoked with the -exec option has ended. In particular, -print is an option for find , not the executed rm . <> and ; are both surrounded with single quote marks to protect them from interpretation by the shell.

This page was originally published on Tuesday, July 3, 2018.

Читайте также:  Acl права доступа linux

Источник

Как удалить файл через терминал Linux

Эта небольшая заметка ориентирована на совсем начинающих. Сегодня мы рассмотрим как удалить файл linux через терминал. Для более опытных пользователей это элементарная задача, но новичкам надо с чего-то начинать. Знать как работать с файлами в консоли очень важно.

К тому же удаление из консоли дает много преимуществ и большую гибкость. Например, с помощью специальной команды вы можете полностью стереть файл с жесткого диска, так что его уже ни за что невозможно будет восстановить или одной командой с помощью специальных символов, условий или регулярных выражений удалить сотни ненужных файлов в одном каталоге или подкаталогох соответствующих определенному критерию.

В Linux для удаления файлов предусмотрена стандартная утилита rm. Как и все остальные, стандартные утилиты в имени rm тоже заложена определенная идея. Это сокращение от английского слова Remove.

Удаление файлов в Linux

Чтобы удалить файл linux достаточно передать в параметрах команде адрес файла в файловой системе:

Чтобы удалить все файлы, начинающиеся на слово file можно использовать специальный символ *, означает любой символ в любом количестве:

Эта команда удаления файла в linux должна использоваться очень осторожно, чтобы не удалить ничего лишнего. В утилите есть опция -i, которая заставляет программу спрашивать пользователя перед тем, как удалить файл linux:

rm: удалить пустой обычный файл «/home/user/file»?

Если файлов очень много, вы уверены в правильности команды и отвечать каждый раз y неудобно, есть противоположная опция — f. Будут удалены все файлы без вопросов:

Для удаления директорий, вместе с файлами и поддиректориями используется опция -R, например:

Будет удалено все что находиться в папке dir, и эта папка. Только будьте бдительны, чтобы не получился знаменитый патч Бармина:

Не стоит выполнять эту команду в своей системе, как видите, она удаляет все файлы в файловой системе Linux.

Удаление файла в linux также возможно с помощью утилиты find. Общий синтаксис find:

find папка критерий действие

Например, мы хотим удалить файл linux по имени:

find . -type f -name «file» -exec rm -f <> \;

Будут найдены все файлы с именем file в текущей папке и для них вызвана команда rm -f. Можно не вызывать стороннюю утилиту, а использовать действие delete:

find . -type f -name «file» -delete

Удалить все файлы в текущей директории, соответствующие определенному регулярному выражению:

find . -regex ‘\./[a-f0-9\-]\.bak’ — delete

Или удалить файлы старше определенного строка, может быть полезно для удаления старых логов:

find /path/to/files* -mtime +5 -exec rm <> \;

Будет выполнено удаление файлов через терминал все файлы в папке старше 5-ти дней.

Чтобы полностью стереть файл, без возможности восстановления используйте команду shred. Во время удаления файлов с помощью утилиты rm удаляется только ссылка на файл, само же содержимой файла по-прежнему находиться на диске, пока система не перезапишет его новыми данными, а пока этого не случится файл можно легко восстановить. Принцип действия утилиты такой — после удаления файла, его место на диске несколько раз перезаписывается.

Опцией -n — можно указать количество перезаписей диска, по умолчанию используется 3. А если указать опцию -z программа при последней перезаписи запишет все нулями чтобы скрыть, уничтожение файла.

Выводы

Вот и все. Теперь вы знаете как удалить файл в Ubuntu, как видите, делать это не так уж сложно. Если у вас остались вопросы, пишите в комментариях!

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

Источник

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