How to remove/delete a directory in Linux/macOs


There are multiple ways in which you can remove or delete a directory in Linux or macOS using terminal commands, lets see some of them,

Remove directory using rmdir command

rmdir is a command line utility that you can use to delete empty directories, this will work only when the directory is empty, let see an example,

 % mkdir myDir     
 % rmdir myDir
 % 

In the below example we created a directory and add a file in it, now if you try to delete the directory you will get error "Directory not empty"

 % mkdir myDir     
 % cd myDir 
 % touch myFile.txt
 % cd ..

 % rmdir myDir
rmdir: myDir: Directory not empty
 % 

Remove directory using rm command

If you want to remove a directory which contains directories and files in it you can make use of rm -r command,

 % rm myDir 

rm: myDir: is a directory

 % rm -r myDir
 % 

If you get no error and you are returned to the prompt returns, you command was successfully executed and the dir should be deleted.

remove or delete directory using linux command
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.