Search code examples
croncron-task

How to remove empty folders and subfolders using cronjob


I found a script online that works when entered into custom cronjobs on cpanel.

When i run this script, the code deletes the folder and everything within it.

 rm -rf public_html/storage_area/images/

I would like to delete empty sub-folders housed within the images folder and not the actual images folder itself.

I do not have much technical knowledge so any help would be much appreciated. I have tried a few php scripts that i found online but did not have much luck so if there is something that exists even better.

Thank you for any assistance.


Solution

  • You just need to modify the command a bit.

    If you need to remove only files inside that folder you can use,

    rm -rf public_html/storage_area/images/*.* 
    

    The *.* will only remove files within the folder public_html/storage_area/images/ having an extension.

    If you need to remove files and sub folders, then you need to use

    rm -rf public_html/storage_area/images/* 
    

    If you only need to remove sub folders which are empty, you can use

    find  -type d -empty -delete
    

    Before running the above command, you may need to verify whether the command is only returning empty folders. For that you can use,

     find public_html/storage_area/images/ -type d -empty -print