Delete a Directory using Mac Terminal Command


In order to delete a directory (dir) on your Mac running macOS via the Terminal application you can make use of the rmdir command

Syntax:
rmdir path-of-the-directory - if the dir is empty
rm -r path-of-the-directory
Example:

Let's first create a directory in the Desktop and name it myDir, let's add a few files to it, I use the touch command just to create blank files abc.txt, xzy.csv so that the directory is not empty.

% mkdir myDir
% cd myDir
% touch abc.txt
% touch xyz.csv
% cd ..
% rmdir myDir 
rmdir: myDir: Directory not empty

As you can see the myDir directory is not deleted as it is not empty, in order to delete the directory with files and folders in it you can make use of rm command with -r parameter.

Example:
code2care@mac Desktop % rm -r myDir
remove dir on mac using rm command
remove dir on mac using rm command

Troubleshooting steps:

Note if the directory does not exist and you use the rmdir command you will get a "No such file or directory" error

code2care@mac Desktop % rmdir mydir1
rmdir: mydir1: No such file or directory
No such file or directory
No such file or directory

If the object you are trying to delete and it's not a directory - i.e. a file you will get an error like - Not a directory

code2care@mac Desktop % rmdir myfile.txt 
rmdir: myfile.txt: Not a directory

Options that you can use with rm command

  • -r :Recursive: remove directories and their contents recursively
  • -f :Force: ignore nonexistent files, never prompt
  • -i :Interactive: prompt before every removal
  • -l :Interactive: only prompt before removing more than three files
  • -r :Verbose: explain what is being done
Directory is not empty
Directory is not empty

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap