Linux delete all file in folder

Delete All Files of a Directory in Linux

Here is a quick Linux command tips on deleting the contents of a directory, not the directory itself.

At times you’ll need to delete all the files of a directory. Not the directory itself but the contents of the directory. You could do it to clean up a project, free up space or for any other purpose.

To empty a directory, you use the following command:

The wild card means everything here. So, you are instructing the rm command to remove everything in the given directory.

Please note that this is different than using rm on the directory name directly without /* . If you use rm -r dir , it will delete the directory along with its contents. That’s not always desirable. Is it?

Let’s see about deleting all the contents of a directory in detail.

Properly removing all files in a directory

Linux command line does not have a recycle bin. You have to be careful while deleting files. And if you have to remove multiple files using wildcard, you must be extra cautious.

This is why I advise switching to the directory you want to empty and then using the rm command. This reduces the risk of accidentally deleting the contents of a wrong directory.

Step 1: Go to the desired directory

Use the cd command to switch to the directory you want to empty.

For example, I am going to delete all the contents of the /home/abhishek/sample directory. So, I switch to it first.

It’s good to ensure that you are in the current directory:

Switch to the directory to delete its contents

Step 2: List the directory contents

You should check the directory contents to ensure that you are not deleting any important files. I advise showing hidden files as well.

If there are sub-directories, please ensure nothing important is in there.

List directory contents

Step 3: Delete all files and folders in the directory

Once you are sure that nothing important is in the directory, it is time to delete the contents.

You can use the rm command like this:

Which is a way of instructing the rm command to delete everything it sees in the current directory recursively. The recursive option -r is essential for removing sub-directories.

Sometimes, there are write protected files and then you’ll be asked to confirm the removal. To avoid that, you can include the forced delete option -f .

Delete all files of a directory in Linux

To delete only the hidden files, you can additionally run this command:

Deleting hidden files

Conclusion

While deleting all the contents of a directory without deleting the directory itself seems like an easy job, things get a bit complicated if there are hidden files and folders.

Читайте также:  Структура файловой системы ос linux кратко

In those cases, you have to run rm -rf .* after rm -rf * .

I hope you liked this quick little Linux command line tip. Let me know if you have questions or suggestions.

Источник

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.

Источник

Linux Delete All Files in Current Directory

You may need to delete files from your directory to free up space, clean up a project, or remove malware files. In this tutorial, we will learn how to delete all files in the current directory in Linux.

Читайте также:  Установка webmin linux mint

Delete all files in the directory

To delete all files in the directory use rm command followed by the path to the directory and a wildcard character «*».

This command will delete all files in the directory, but it will not delete any subdirectories or their contents. to delete subdirectories as well, you can add the «-r» flag to the command to make it recursive.

With that note: In Linux, it is best practice to navigate to a desired directory and perform the action from the current directory. Using an absolute path is more prone to accidentally choosing the incorrect path and may end up deleting the wrong files.

To delete all files in the directory /home/ubuntu/mydata/, type:

rm delete all files in a directory

Here all the non-hidden files in the directory are deleted. However, it returns an error for sub-directories. On a side note, you can exclude a specific file from deletion by rm -v !(filename.txt).

To remove all files and sub-directories from the directory /home/ubuntu/mydata, type:

rm delete all files and subdirectories in a directory

You can verify using ls -al /home/ubuntu/mydata to confirm all files and subdirectories in it are deleted.

Delete all files in the current directory

As mentioned before safest way would be to navigate to the directory and delete files from the current directory.

1. Navigate to the Directory

Use cd command to change the directory. For example, we are using /home/ubuntu/mydata.

Change to /home/ubuntu/mydata:

change to directory where the content needs to be deleted

Use pwd command to confirm the current path:

confirm current path

This will print out the absolute path of the directory.

2. List directory contents

List the directory content to make sure you going to delete the right files. For listing all files in the current directory use ls -al command.

list the directory contents

This command will list all the contents of the directory /home/ubuntu/mydata such as sub-directories and files ( including hidden files).

3. Delete all files in the Directory

Once we confirm we are in the right directory, we can delete all files in the current directory using rm -rv *.

from current directory remove all files and sub directories

This command will delete all the files and subdirectories in the current directory. The -v option gives a verbose output to show removed files and the directory.

Note: If you have any write-protected files and directories rm will prompt.

You can verify by typing ls -al

If you have any manually created hidden files, to remove them all use rm -rv .* command. This is because the asterisk (*) does not match files that begin with a dot, which are hidden files.

remove all files and subdirectories including manually created hidden files from a directory.

The individual directories . (indicates current directory) and .. (indicates parent directory ) will be still there — which cannot be deleted. No harm in keeping it.

Delete all files in directory without prompt

Use rm -rf * to delete all files in the directory without any prompt. Prompt occurs when rm encounters any errors such as write access protection. This option helps to avoid it.

For example, to delete all files in the directory /home/ubuntu/mydata without any prompt, type:

delete all files in a directory without prompt

We verify that the files have been deleted by running:

Conclusion

In this tutorial, we learned how to delete all files in a directory in Linux. Be cautious when using rm with asterisk command, as it can potentially delete important files. Always double-check the files you want to delete before executing the command.

Читайте также:  Linux размер текущей папки

If this resource helped you, let us know your care by a Thanks Tweet. Tweet a thanks

Источник

Как удалить все файлы в папке Linux

Время от времени стоит чистить систему, чтобы она не засорялась ненужными данными. В случае с дистрибутивами Linux есть несколько способов удаления файлов, применимых в разных ситуациях.

Из данной статьи вы узнаете, как удалить все файлы в папке Ubuntu, в том числе скрытые и не скрытые. Заодно мы разберем важные нюансы данной процедуры, упомянув несколько способов чистки.

Как удалить все файлы в папке Linux

Многие действия в данной операционной системе удобно выполнять с помощью команд в терминале. Чистка содержимого папок тоже относится к их числу. Для начала предлагаем посмотреть полный список файлов в конкретном каталоге, на примере ~/Downloads:

find ~/Downloads -maxdepth 1 -type f

WDS53SE3p2fPeNb3+f64hJQU5y2WzAAAAAElFTkSuQmCC

Файлы, название которых начинается с точки, являются скрытыми. Остальные – не скрытые. Простая чистка не скрытых файлов внутри директории осуществляется такой командой:

KzQAAAABJRU5ErkJggg==

Чтобы стереть все файлы, даже скрытые, выполните эту команду:

p7ceCC3TODQAAAABJRU5ErkJggg==

Для просмотра всех файлов и каталогов в выбранном местоположении, в том числе и скрытых, подойдет команда find без параметров. Например:

Pxc+PyGgnnu4AAAAAElFTkSuQmCC

Полная чистка директории со всеми вложенными файлами и папками (даже скрытыми) осуществляется другой командой:

Похожие записи

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

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

6 комментариев к “Как удалить все файлы в папке Linux”

Спасибо за статью. А как можно настроить, что при запуске команды «rm -rf » данные не удалялись напрямую, а складывались во временную папку или в корзину, как сделано в Windows? Чтобы я потом сам удалял из корзины, после того, как убедился что ничего не поломалось после удаления. Ответить

Осознаю, не панацея. Но если устроит, то создайте такой скрипт: #!/usr/bin/bash TRASH=»/home/$USER/.trash/» if [ ! -d $TRASH ] ; then
# echo $TRASH
mkdir -p $TRASH
fi for file in $*
do
if [ -f $file ] ; then
# echo $file
mv $file $TRASH
fi
done Назовите его rm и поместите в директорий, в котором находятся Ваши личные запускаемые файлы и скрипты. У меня Debian/MATE. Такой директорий находится в домашнем директории и называется bin. Кроме того, путь к этому поддиректорию у меня задаётся в файле .bashrc. И этот путь размещён раньше пути к директорию /usr/bin/, где находится сстемная утилита rm. Таким образом при выполнении команды rm будет «срабатывать» Ваш скрип, а не системная утилита. И да! После создания скрипта не забудьте сделать его исполняемым — chmod +x. В скрипте я оставил пару команд echo. Это на тот случай, если Вам захочется с ним поиграться. Просто закомментируйте команды mkdir и mv и удалите комментарий у рядом стоящих команд echo. Ответить

Можно просто использовать gio trash: Usage:
gio trash [OPTION…] [LOCATION…] Move/Restore files or directories to the trash. Options:
-f, —force Ignore nonexistent files, never prompt
—empty Empty the trash
—list List files in the trash with their original locations
—restore Restore a file from trash to its original location (possibly recreating the directory) Note: for —restore switch, if the original location of the trashed file
already exists, it will not be overwritten unless —force is set. Ответить

Не буду даже пробовать такое. С самого начала следовало бы написать, насколько это безопасно и почему (и какие) файлы должны быть удалены из системы. Ответить

Источник

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