Removing Directories With rm
rm
is a command-line utility for deleting files and directories. Unlike rmdir
the rm
command can delete both empty and non-empty directories.
By default, when used without any option rm
does not remove directories. To delete an empty directory, use the -d
(--dir
) option and to delete a non-empty directory, and all of its contents use the -r
(--recursive
or -R
) option.
For example to delete a directory named dir1
along with all of its contents you would type:
$ rm -r dir1
If a directory or a file within the directory is write-protected, you will be prompted to confirm the deletion. To remove a directory without being prompted, use the -f
option:
$ rm -rf dir1
To remove multiple directories at once, invoke the rm
command, followed by the names of the directories separated by space. The command below will remove each listed directory and their contents:
$ rm -r dir1 dir2 dir3
The -i
option tells rm
to prompt you to confirm the deletion of each subdirectory and file. If the directory contains a lot of files, this can be a little annoying, so you may consider using the -I
option what will prompt you only once before proceeding with the deletion.
$ rm -rI dir1
To remove the directory type y
and hit Enter
.
rm: remove 1 argument recursively? y
You can also use regular expansions to match and delete multiple directories. For example, to remove all first-level directories in the current directory that ends with _bak
, you would use the following command:
$ rm -r *_bak
Using regular expansions when removing directories may be risky. It is recommended first to list the directories with the ls
command so that you can see what directories will be deleted before running the rm
command.