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

FileTerminalDirectoryRmRmdir

File Problem Overview


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.

File Solutions


Solution 1 - File

rm -rf some_dir

-r "recursive" -f "force" (suppress confirmation messages)

Be careful!

Solution 2 - File

rm -rf *

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.

Solution 3 - File

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.

Solution 4 - File

I was looking for a way to remove all files in a directory except for some directories, and files, I wanted to keep around. I devised a way to do it using find:

find -E . -regex './(dir1|dir2|dir3)' -and -type d -prune -o -print -exec rm -rf {} \;

Essentially it uses regex to select the directories to exclude from the results then removes the remaining files.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNoneView Question on Stackoverflow
Solution 1 - FileJim LewisView Answer on Stackoverflow
Solution 2 - FilePrineView Answer on Stackoverflow
Solution 3 - FileAntal Spector-ZabuskyView Answer on Stackoverflow
Solution 4 - Filemsantoro12View Answer on Stackoverflow