How do I remove a directory in Unix?

last updated in Categories , , , , ,

I am a new macOS Unix user. How do I remove a directory in Unix using the terminal applications?

Introduction: Everything is a file in Unix including the directory. A directory is nothing but a group of files (or data). One can group files as per our needs and setup. For example, I can store all of my videos in ~/Videos/ directory. You can use any one of the following commands to remove the directory in Unix (also known as a folder in Microsoft Windows operating system):

  1. rmdir command – Remove the specified empty directories on Unix
  2. rm command – Remove directories even if it is not empty in Unix

Let us see how to remove directories in Unix using the command line.

How do I remove a directory in Unix using the CLI?

The syntax is
rmdir dirNameHere
First, open the terminal Application. Say you want to remove a directory named banking-data in the home directory, run:
rmdir banking-data
OR
rmdir $HOME/banking-data
Verify directory deleted from the system with help of ls command:
ls
ls -l banking-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 /tmp/delta/:

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

How to delete a directory in Unix even when it is not empty

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 -r option to the rm command. The rm command syntax is as follows to delete a directory in Unix:
rm -r /path/to/dir/
rm -rf myDirName
rm -rfv /path/to/dir
rm -rfv ~/foo/
rm -ri myDirName

Remove a directory in Unix using command line Terminal app
Where,

  • -r – Remove directories and their contents recursively on Unix
  • -f – Forceful option i.e. attempt to remove the files without prompting for confirmation, regardless of the file’s permissions.
  • -v – Be verbose. Show what rm command doing with given directory/file names on Unix
  • -i – Request confirmation before attempting to remove each file, regardless of the file’s permissions, or whether or not the standard input device is a terminal.

Conclusion

This page demonstrated how to delete both empty and non-empty directories along with all files/sub-directories using rm and rmdir command on Unix operating systems.

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!