Is there a way reverse of what mkdir -p option does?

The reversal of the mkdir -p command would be rmdir -p. rmdir -p will remove the folder structure up till the folder is not empty. You should be able to use rmdir instead of mkdir on your command:

rmdir -p $HOME/.local/my/sub/directories/1/2/3

You can also specify wildcards like if your $HOME/.local/my/sub/ contained like directories1, directories2 and directories3 for example, it could be done as:

rmdir -p $HOME/.local/my/sub/directories*/1/2/3

or

rmdir -p $HOME/.local/my/sub/*/1/2/3

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.

rmdir: failed to remove directory '/home/user/.local/my/sub': Directory not empty

Hope this helps!


There are two ways I'd attempt this. The easy method is as follows:

# Command to return only empty directories in the current directory:
find . -type d -empty -print

Now on my version of Ubuntu, I can simply perform the following:

# Find empty files, and delete them:
find . -type d -empty -delete

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:

#!/bin/bash

for i in */ .*/ ; do 
    echo -n $i": " ; 
    (find "$i" -type f | wc -l) ; 
done