How To Delete a Directory in Linux

By | 2018-06-28

There are a few ways you can delete a directory on Linux and UNIX systems. If you are using a desktop environment, you can probably right click on it in your file manager and select the appropriate option. If you are using the command line, you can use either the rm command, or the rmdir command.

Delete a Directory Using rmdir

The safest way to delete a directory is with rmdir because it will not allow you to delete a directory that has files or other directories in it.

tyler@desktop:~/dir$ rmdir a
rmdir: failed to remove 'a': Directory not empty

Obviously, you will need to remove or relocate the directory’s contents before rmdir will allow you to delete it. Use the rm command to delete any files inside of it.

tyler@desktop:~/dir$ rmdir a
rmdir: failed to remove 'a': Directory not empty
tyler@desktop:~/dir$ cd a
tyler@desktop:~/dir/a$ ls
b
tyler@desktop:~/dir/a$ rm b
tyler@desktop:~/dir/a$ cd ..
tyler@desktop:~/dir$ rmdir a
tyler@desktop:~/dir$

You may run into the situation where it appears empty. This is because it has a hidden file. Files beginning with . are not displayed by default. The -a and -A options will show hidden files.

tyler@desktop:~/dir$ cd a
tyler@desktop:~/dir/a $ ls
tyler@desktop:~/dir/a $ ls -a
.  ..  .hidden
tyler@desktop:~/dir/a$ ls -A
.hidden
tyler@desktop:~/dir/a$ rm .hidden 
tyler@desktop:~/dir/a$ cd ..
tyler@desktop:~/dir$ rmdir a
tyler@desktop:~/dir$

The difference between -A and -a is -a shows the two special directory entries . and ... The former is the directory you are currently in, while the latter is the parent directory.

Delete a Directory Using rm

This is the quick and easy way. To delete a directory and all if it’s contents, use rm -rf. This command will remove a directory and everything in it with no questions asked, so be careful!

tyler@desktop:~/dir$ rm -rf a
tyler@desktop:~/dir$ 

The f instructs find to remove everything without prompting. It will override any missing write permissions as well. The r option means recursively remove directories. That is a fancy way of saying remove the directory and everything in it.

A safer way is to use the i option. Adding i instructs rm to prompt you before deleting each file or directory.

tyler@desktop:~/dir$ rm -ri a
rm: descend into directory 'a'? y
rm: remove regular empty file 'a/b'? y
rm: descend into directory 'a/c'? y
rm: remove regular empty file 'a/c/d'? y
rm: remove directory 'a/c'? y
rm: remove directory 'a'? y
tyler@desktop:~/dir$