How do I delete a directory with bash – rmdir is one of the useful commands in bash, it’s one of those commands that tends to be used almost everyday by Techies, like support teams. What you first have to understand is that the command will be slightly different if the folder has files ( contents).
So to remove a directory that is empty, you would use the command –
This would delete the folder fooRemove, with no prompt or message to confirm that it was done. In the example above, you would replace “/foo/fooRemove” with the path of the directory you want to delete. Although what you may also see when using this command is an error message, like the one below –
Error message –
rmdir: failed to remove '/foo/fooRemove/': Directory not empty
This happens when there is content in the folder, by content I mean files, including hidden ones. So, what if there are files in the folder and you still want to delete the folder and everything inside of it.
Before you start thinking of running the command to remove a folder it would be a good idea to first check to see if the file is really there in via a BASH command, we put together the guide to teach you the basics.
Well, we would need to add a couple of parameters to the command:
rmdir -rf /foo/fooRemoveContents or try rmdir -r -f /foo/fooRemoveContents
In the above example, the “/foo/fooRemoveContents” is the target directory, the one you want to get rid of. So, with a little help from the added -r and -f it will delete the folder and its contents by force, ‘-f’ is short for –force and the ‘-r’ is for –recursive.
Error message –
You may also see and error like the one below –
rmdir: failed to remove 'foo': Not a directory
This error tells you that the folder that you are trying to delete is not actually a folder or something recognised by rmdir to be a directory. rmdir can not be use to delete files only, the files have to be in a folder and then rmdir will remove the whole lot.
However, more often then not just using the ‘-r’ parameter in the command would be enough to do the job. It would also be safer, as using the ‘-f’ or –force actually overrides some sanity checks and prompting. But this is for you to decide as sometime is it safer to use the force option, especially when working on remote systems.
If you need help with what parameters can work with the rmdir command you can run –
This will list all of your options, below I have provided the output of the rmdir –help commend, to save you time.
Usage: rmdir [OPTION] ... DIRECTORY... Remove the DIRECTORY(ies), if they are empty. --ignore-fail-on-non-empty ignore each failure that is solely because a directory is non-empty -p, --parents remove DIRECTORY and its ancestors; e.g., 'rmdir -p a/b/c' is similar to 'rmdir a/b/c a/b a' -v, --verbose output a diagnostic for every directory processed --help display this help and exit --version output version information and exit