how to delete a folder or directory in linux

The Linux command to delete a folder or directory is the same as the one to delete a file. You can use the rm command to delete both files and folders. Deleting an empty directory is easy enough but if you try to remove a directory that has files in them, you will get an error.

deleting an empty folder

bash$ rm /path/to/folder
rm: cannot remove 'folder/': Is a directory

You will need to delete or remove all the contents of the folder before you can delete it. If you want to preserve the contents of the folder, then you can move the files to another location and then delete the folder.

deleting folders with content

If you want to delete the folder including all the files and sub-folders within it, then you will need to use the –recursive or -r option with the rm command. This will delete the files and folders recursively.

bash$ rm -r /path/to/folder/name/

By default, the rm command will prompt you before deleting each and every file. If you have a lot of files in the folder, then this could get cumbersome. In order to avoid getting prompted each time, you can use the –force or -f option.

bash$ rm -fr /path/to/folder/name/

deleting folders with rmdir

Although you can use the rm command to delete folders, it is primarily designed to delete files and not folders. However, you can use it just the same as you saw above. The command to remove or delete directories is rmdir.

But, rmdir will remove only empty directories or folders just as the rm command. The rmdir command has a –parents or -p option, which will remove the folder and its parents or ancestors. You can specify the last empty sub-directory and then delete it and its parents.

bash$ rmdir -p a/b/c

The above command will delete the directory 'c', then 'b' and finally 'a'.

I find the rm command to be much more useful and easier than the rmdir command. But you could use whichever you feel the most comfortable with.