In bash all I know is that
rmdir directoryname
will remove the directory but only if it's empty. Is there a way to force remove subdirectories?
The following command will do it for you. Use caution though if this isn't your intention as this also removes files in the directory and subdirectories.
rm -rf directoryname
rm -r directoryname
.
Commented
Aug 17, 2012 at 3:35
rm: invalid option -- r
error when trying to delete a directory with rm -r <directoryname>.
rm -rf directoryname
coz you wouldn't want your script to pause execution, because it's waiting for user input. Of course, you have to be sure that deleting the directory would do no harm.
if rm -rf directoryname
fails you, try using rm -R -f directoryname
, or rm --recursive -f directoryname
.
If you are not having any luck with these, you should consider reinstalling rm or switching shells.
man rm
to view my options on recursive deletion and the force options.
Commented
Nov 11, 2015 at 18:38
rm
man page list -r
? What does it do? (Try it in a directory that you create just for testing purposes, with only dummy files (and maybe subdirectories) in it.) What operating system are you using?
Commented
Nov 11, 2015 at 19:08
rm -r
doesn't work, that would be an OS issue, not a shell issue. (Strictly speaking, it would be an issue with the version of rm
that you're using, so you could address it by installing a different version of rm
, or searching your system to see whether you already have a different version of rm
in some directory other than /bin
.)
Commented
Nov 11, 2015 at 21:34
man rm
in my terminal, it gave me a text file with the less
text viewer. I scrolled found an indented entry with a whole that had the -R and --recursive options cozied up with the -r option, signifying that all of those arguments are identical.
Commented
Nov 11, 2015 at 22:38
sudo rm -r directoryName
? The unwritten rules of the basic commands is that -r
will allow a program to run recursively on every file your filesystem (starting where ever you choose!) and that -f will forcefully do things, even if it's dangerous. 'cd', 'mv', 'ls' mostly holds this principle true. ls -r /
is gonna be a duzie, and cp -rf / /dev/null
will destroy everything on your filesystem. <--Never run that command!
Commented
Nov 11, 2015 at 22:49
Other answers show how to completely remove a directory’s content, but IMO they don’t address the literal question of the original post — that is, how can one delete subdirectories (as opposed to usual files). In other words, how can one delete empty directory structures while keeping subdirectories containing files ?
This can be achieved with find
:
find directoryname -type d -delete
This command will recursively search for directories (-type d
) through directoryname
and -delete
them only if their subdirectories or themselves don’t contain any files.