How to delete file from terminal linux

How to delete and remove files on Ubuntu Linux

Command to delete and remove files on Ubuntu Linux

The syntax is as follows for the rm and unlink command to remove files on Ubuntu Linux:

  1. Open the Ubuntu terminal application (bash shell)
  2. Type any one of the following command to delete a file named ubuntu.nixcraft.txt in the current directory
  3. rm ubuntu.nixcraft.txt
    OR
    unlink ubuntu.nixcraft.txt

Let use see all rm command options to delete and remove files on Ubuntu Linux.

WARNING : Do not type sudo rm -R / or sudo rm -r / or sudo rm -f /* or sudo rm —no-preserve-root -rf / as it removes all the data in the root directory. Avoid data loss and you should not execute them!

Delete multiple files on Ubuntu Linux

Type the following command to delete the file named dellLaptopSerials.txt, tom.txt, and dance.jpg located in the current directory:
vivek@nixcraft:

$ rm dellLaptopSerials.txt tom.txt dance.jpg
You can specify path too. If a file named dellLaptopSerials.txt located in /tmp/ directory, you can run:
vivek@nixcraft:

$ rm /tmp/dellLaptopSerials.txt
vivek@nixcraft:

$ rm /tmp/dellLaptopSerials.txt /home/vivek/dance.jpg /home/vivek/data/tom.txt

Ubuntu Linux delete a file and prompt before every removal

To get confirmation before attempting to remove each file pass the -i option to the rm command on Ubuntu Linux:
vivek@nixcraft:

$ rm -i fileNameHere
vivek@nixcraft:

$ rm -i dellLaptopSerials.txt

Force rm command on Ubuntu Linux to explain what is being done with file

Pass the -v option as follows to get verbose output on Ubuntu Linux box:
vivek@nixcraft:

$ rm -v fileNameHere
vivek@nixcraft:

$ rm -v cake-day.jpg

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Ubuntu Linux delete all files in folder or directory

You need to pass the following options:
vivek@nixcraft:

$ rm -rf dir1
vivek@nixcraft:

$ rm -rf /path/to/dir/
vivek@nixcraft:

$ rm -rf /home/vivek/oldschoolpics/
It will remove all files and subdirectories from a directory. So be careful. Always keep backups of all important data on Ubuntu Linux.

Ubuntu Linux delete file begins with a dash or hyphen

If the name of a file or directory or folder starts with a dash ( — or hyphen — ), use the following syntax:
vivek@nixcraft:

$ rm — -fileNameHere
vivek@nixcraft:

Читайте также:  При загрузке windows 0х000000ed

$ rm — —fileNameHere
vivek@nixcraft:

$ rm -rf —DirectoryNameHere
vivek@nixcraft:

$ rm ./-file
vivek@nixcraft:

$ rm -rf ./—DirectoryNameHere

Do not run ‘ rm -rf / ‘ command as an administrator/root or normal Ubuntu Linux user

rm -rf (variously, rm -rf /, rm -rf *, and others) is frequently used in jokes and anecdotes about Ubuntu Linux disasters. The rm -rf / variant of the command, if run by an administrator, would cause the contents of every writable mounted filesystem on the computer to be deleted. Do not try these commands on Ubuntu Linux :
vivek@nixcraft:

$ rm -rf /
vivek@nixcraft:

Conclusion

The rm command removes files on Ubuntu Linux. The rm command options are as follows:

  • -f : Remove read-only files immediately without any confirmation.
  • -i : Prompts end-users for confirmation before deleting every file.
  • -v : Shows the file names on the screen as they are being processed/removed from the filesystem.
  • -R OR -r : Removes the given directory along with its sub-directory/folders and all files.
  • -I : Prompts users everytime when an attempt is made to delete for than three files at a time. Also works when deleting files recursively.

See rm command man page by typing the following man command:
% man rm
% rm —help

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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

Want to improve this question? Update the question so it’s on-topic for Stack Overflow.

Closed 6 years ago .

From 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 any 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 terminal, not Microsoft DOS or linux.

4 Answers 4

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

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.

Источник

How To: Linux / UNIX delete a file using rm command

H ow do I delete a file under a Linux / UNIX / *BSD / AIX / HP-UX operating system using command line options?

To remove or delete a file or directory in Linux, FreeBSD, Solaris, macOS, or Unix-like operating systems, use the rm command or unlink command. This page explains how to delete a given file on a Linux or Unix like system using the command line option.

Tutorial details
Difficulty level Easy
Root privileges No
Requirements rm and unlink command on Linux or Unix
Est. reading time 4 minutes

Syntax: rm command to remove a file

rm (short for remove) is a Unix / Linux command which is used to delete files from a filesystem. Usually, on most filesystems, deleting a file requires write permission on the parent directory (and execute permission, in order to enter the directory in the first place). The syntax is as follows to delete the specified files and directories:

  • -f : Forcefully remove file
  • -r : Remove the contents of directories recursively

When rm command used just with the file names, rm deletes all given files without confirmation by the user.

  • No ads and tracking
  • In-depth guides for developers and sysadmins at Opensourceflare✨
  • Join my Patreon to support independent content creators and start reading latest guides:
    • How to set up Redis sentinel cluster on Ubuntu or Debian Linux
    • How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
    • How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
    • A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
    • How to protect Linux against rogue USB devices using USBGuard

Join Patreon

Warning : Be careful with filenames as Unix and Linux, by default, won’t prompt for confirmation before deleting files. Always keep verified backups of all critical files and data.

Unix Remove or delete a file example

Say you have a file named abc.txt and you want to remove it:
$ rm abc.txt

Linux delete multiple files

Delete three files named foo.mp4, bar.doc, and demo.txt, run:

Linux recursively delete all files

Remove all files and sub-directories from a directory (say deltree like command from MS-DOS world), enter:
$ rm -rf mydir

Linux delete a file and prompt before every removal

To request confirmation before attempting to remove each file pass the -i option to the rm command:
$ rm -i filename
Sample outputs:

Gif 01: rm command demo

Force rm command to explain what is being done with file

Pass the -v option as follows:
$ rm -v moiz.list.txt bios-updates.doc
removed ‘moiz.list.txt’
removed ‘bios-updates.doc’

How to delete empty directories

To remove empty directory use rmdir command and not the rm command:
$ rmdir mydirectory
$ rmdir dirNameHere
$ rmdir docs

How to read a list of all files to delete from a text file

The rm command is often used in conjunction with xargs to supply a list of files to delete. Create a file called file.txt:
$ cat file.txt
List of to delete:

Now delete all file listed in file.txt, enter:
$ xargs rm

How do I delete a file named -foo.txt or a directory named -bar?

To delete a file called -foo.txt :
rm — -foo.txt
OR
rm — ./-foo.txt
To delete a directory called -bar :
rm -r -f — -bar
The two — dashes tells rm command the end of the options and rest of the part is nothing but a file or directory name begins with a dash.

Never run rm -rf / as an administrator or normal UNIX / Linux user

WARNING! These examples will delete all files on your computer if executed.

$ rm -rf /
$ rm -rf *

rm -rf (variously, rm -rf /, rm -rf *, and others) is frequently used in jokes and anecdotes about Unix disasters. The rm -rf / variant of the command, if run by an administrator, would cause the contents of every writable mounted filesystem on the computer to be deleted. Do not try these commands.

Conclusion

You learned how to delete files on Linux and Unix-like operating systems. Here are all important options for GNU rm command (read man page here)

Remove files command summary

Option Description
-f Ignore nonexistent files and arguments, never prompt
-i Prompt before every file removal
-I Prompt once before removing more than three files, or when removing recursively; less intrusive than -i, while still giving protection against most mistakes —interactive[=WHEN] prompt according to WHEN: never, once (-I), or always (-i); without WHEN, prompt always
—one-file-system when removing a hierarchy recursively, skip any directory that is on a file system different from that of the corresponding command line argument
—no-preserve-root do not treat ‘/’ specially
—preserve-root[=all] do not remove ‘/’ (default); with ‘all’, reject any command line argument on a separate device from its parent
-r remove directories and their contents recursively
-R same as above
-d rmove empty directories
-v Explain what is being done

🐧 Get the latest tutorials on Linux, Open Source & DevOps via

Источник

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

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

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

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

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

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

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

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

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

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

rm -f /home/user/file*

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

rm -Rf /home/user/dir

Будет удалено все что находиться в папке 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, как видите, делать это не так уж сложно. Если у вас остались вопросы, пишите в комментариях!

Источник

Читайте также:  Microsoft technet windows update
Оцените статью