Home > Back-end >  Remove dirs from parent dir without deleting parent directory (Linux)
Remove dirs from parent dir without deleting parent directory (Linux)

Time:01-27

I am using the following command to remove all dirs older than 1 minute from the following path:

find /myhome/me/xyz/[0-9][0-9]/[0-9][0-9][0-9][0-9]/my_stats/ -mmin 1 -exec rm -rf {} \;

folder structure : /home/myhome/me/xyz/<2 digit name>/<4 digit name>/my_stats/

There could be multiple dirs or a single dir inside my_stats. The issue is when there is a single folder inside my_stats, the find command is deleting the my_stats dir as well.

Is there a way to solve this? Thanks

CodePudding user response:

If I understand your question correctly you are probably looking for this:

find /myhome/me/xyz/[0-9][0-9]/[0-9][0-9][0-9][0-9]/my_stats/ -mmin  1 -maxdepth 1 -mindepth 1 -type d -exec rm -rf {} \;

The -mindepth 1 parameter is what excludes the my_stats directory from the listing, as it is located at depth 0.

The -maxdepth 1 parameter will not show subdirs of subdirs (you are deleting their parents recursively anyway).

The -type d parameter limits the output to directories only, not ordinary files.

  • Related