How To Remove or Delete A Directory In Linux? – POFTUT

How To Remove or Delete A Directory In Linux?

Linux provides different commands in order to remove or delete directories and files. But in some cases, this may not work as expected and we can get a message like rmdir: 'dir' Directory no empty which simply means when we try to delete a directory with rmdir command it is not completed. In this tutorial, we will learn how to remove and delete an empty or full directory.

Remove with rm -Rf Command

The most used command to delete a directory with its content is rm command. But rm command is not enough without options -Rf. This will force the deletion of given directories in a recursive manner. In this example, we will delete the directory named backup

Remove with Verbose Information

Deleting directory with its children will not provide verbose information by default. But we can print detailed information about the operation with verbose option -v like below.

Remove with Verbose Information

Remove with Verbose Information

Confirm Before Deleting Directory

If we will delete directories those contain some sensitive ones we may need to confirm before deleting them. We can use -i option which will ask for a removal for confirmation. In this example, we will delete the directory named poftut1 which is not empty. For each directory and files inside poftut1 the remove directory FILE or DIRECTORY NAME will be asked to use. In order to approve we can enter y or yes to deny we can use empty answer which is just enter or n or no.

Confirm Before Deleting Directory

Confirm Before Deleting Directory

Remove Multiple Directories At Once

We may want to remove multiple directories with a single rm command. We do not have to run rm command multiple times for different directory names. We can provide all directories we want to remove in a single rm command. We can also provide the path of the directory like /mnt/test etc.

Remove Multiple Directories At Once

Remove Multiple Directories At Once

Remove with Root Privileges

In order to delete a file or directory, we need privileges. If the directory is owned by root user and we are not we can not delete the directory. So we need to get root privileges with sudo command like below.

Remove with Python

We can also use some python script or commands in order to delete a directory please look following example where we will use os module remove() function.

How To Delete and Remove File and Directory with Python?

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)