How do I delete a directory in Linux terminal?

last updated in Categories , , , , ,

I am a new Linux user. How do I delete a directory in Linux terminal?

Introduction: Everything is a file in Linux including the directory. A directory is nothing but a group of files (or data). You can group files as per needs. For example, store all C program files in $HOME/projects/ directory. You can use any one of the following commands to delete a directory in Linux (also known as a folder in the macOS and Microsoft Windows operating system):

  1. rmdir command – Delete the specified empty directories in Linux
  2. rm command – Delete directories even if it is not empty in Linux

Let us see how to delete directories in Linux using the command line.

How to delete a directory in Linux terminal

Say you want to delete a directory named /home/vivek/data/, run:
rmdir /home/vivek/data/
rmdir -v ~/data/

Verify directory deleted from the system with help of ls command:
ls /home/vivek/data/
ls ~/data/

Please note that when attempting to remove a directory using the rmdir command, the directory must be empty. Otherwise, you might see an error message that read as follows on screen when execute rmdir -v /home/vivek/projects/:

rmdir: failed to remove '/home/vivek/projects/': Directory not empty

How do I delete a full directory in Linux?

As I said earlier rmdir command remove the DIRECTORY(ies) if they are empty. But, how do you delete a full directory that has many files and sub-directories? The solutions is to pass the -rf option to the rm command. The syntax is:
rm -r dir1
rm -rf dir2 dir3 /path/to/foo/
rm -rfv /path/to/bar/dir/
rm -rfv /home/vivek/projects/

Delete a directory in Linux terminal
Where,

  • -r – Delete directories and their contents recursively
  • -f – Forceful option i.e. ignore nonexistent files and arguments, never prompt for anything
  • -v – Be verbose. Show what rmdir or rm command doing with given directory
  • -i – Prompt before every removal of file/dir
  • -I – Confirm (display prompt) once before removing more than three files, or when removing recursively; less intrusive than -i, while still giving protection against most mistakes. Useful when working on a large number of files on Linux

Conclusion

This page showed how to delete both empty and non-empty directories along with all files/sub-directories using rm and rmdir command in Linux terminal application.

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

Start the discussion at www.nixcraft.com

Historical Comment Archive

1 comment

    Have a question? Post it on our forum!