Unix command to delete a directory in terminal

last updated in Categories , , , ,

I am a new Unix system user. How do I delete a directory in Unix?

A directory is nothing but a location for storing files on your Unix based system. For example, /home/vivek/Downloads/ stores all downloaded files from the Internet. In Unix, you need to use rmdir command to remove a directory. This page shows how to delete a directory using the rmdir command and rm command.

Unix command to delete a directory

The syntax is as follows:

  1. Open the terminal application
  2. To delete a directory named dir1 that exists in your current working directory, enter: rmdir dir1
  3. If dir1 exists, and is an empty directory, it will be deleted. If the directory is not empty or you do not have permission to delete it, you will see an error message on screen
  4. To remove a full directory named dir2 in Unix including all files and sub-directories, run: rm -rf dir2

Let us see some examples and usage in details.

In Unix, how do I remove a directory?

For example, to eliminate a sub-directory named pics that exists in your current working directory, at the Unix prompt, run:
ls -l
ls -l pics
rmdir pics
ls -l

Unix command delete a directory using terminal
Please note that the directory named “pics” must be empty before you can remove it, and you must have write permission in its parent directory. Use the ls -al pics command to check whether the directory is empty or not. To remove the /home/vivek/fintechdata directory, run:
rmdir /home/vivek/fintechdata
To remove the /data, /data/sales, and /data/sales/fy2003 directories, type:
rmdir -p /data/sales/fy2003

How do I remove a full directory in Unix?

Let us try to remove directory called “data”, enter:
rmdir data
Sample outputs:

rmdir: failed to remove 'data': Directory not empty

If the subdirectory “data” exists in your current directory and it is not empty, you can delete it by entering at the Unix prompt:
rm -r data
How do I remove a full directory in Unix

Conclusion

This page showed how to delete an empty directory as well as how to remove a directory that contains other files or directories. For more info on the rmdir and the rm -r commands, see their man pages here and here. At the Unix shell prompt, run:
man rmdir
man rm

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

    Still, have a question? Get help on our forum!