Home > Software engineering >  Delete files in dir but exclude 1 subdir
Delete files in dir but exclude 1 subdir

Time:03-03

I have a dir that is full of many htm reports that I keep around for 30 days and delete old ones via a cron, but there is one sub-dir I would like to keep longer. So this is the line I made in the cron, but how do I tell it to leave one sub-dir alone.

5 0 * * * find /var/www -name "*.htm*" -type f -mtime  30 -exec rm -f {} \;

Any help is greatly appreciated!

CodePudding user response:

Use -prune to prevent going into a directory that matches some conditions.

find /var/www -type d -name 'excluded-directory' -prune -o -name "*.htm*" -type f -mtime  30 -exec rm -f {} \;

CodePudding user response:

In addition to suggestion below, suggesting to use full path in cron.

Also to use find option -delete in-place of -exec rm -f {} \;. It is somewhat safer.

 -delete
        Delete found files and/or directories.  Always returns true.
        This executes from the current working directory as find recurses
        down the tree.  It will not attempt to delete a filename with a
        "/" character in its pathname relative to "." for security
        reasons.  Depth-first traversal processing is implied by this
        option.  The -delete primary will fail to delete a directory if
        it is not empty.  Following symlinks is incompatible with this
        option.
5 0 * * * /usr/bin/find /var/www -type d -name 'excluded-directory' -prune -o -name "*.htm*" -type f -mtime  30 -delete
  • Related