I Use Ubuntu 18.04, 19.10
using #!/bin/bash
script how to remove the directories if they are empty from far end and stop at the directory having any file/files.
say.. I have created multiple directories with the below command
mkdir -p $HOME/.local/my/sub/directories/1/2/3
lateron during the time I have created lot of files in all directories starting from the directory "my to 1/2/3".
After some time I have deleted all the files in the directories "my", "directories", "1", "2", "3". Note that directory sub
is having some files..
mkdir -p
option will see if there are parent directories in the command mkdir -p $HOME/.local/my/sub/directories/1/2/3
and its safe.
Question: like above is there any command to see if the directories are empty and delete from far end and stop at directory sub
I mean $HOME/.local/my/sub
The reversal of the
mkdir -p
command would bermdir -p
.rmdir -p
will remove the folder structure up till the folder is not empty. You should be able to usermdir
instead ofmkdir
on your command:You can also specify wildcards like if your
$HOME/.local/my/sub/
contained likedirectories1
,directories2
anddirectories3
for example, it could be done as:or
If any folder as it is removing them contains data or another folder you will receive an error message that the directory is not empty and stops.
Hope this helps!
There are two ways I'd attempt this. The easy method is as follows:
Now on my version of Ubuntu, I can simply perform the following:
Otherwise, you can create some script with a logic to count files in a directory, and delete them. Here is a starting point for counting files in sub-directories:
This is closer to the reverse of
mkdir -p
:Example: