Mike Mike - 2 months ago 19
Linux Question

How do I delete all files/driectories within my directory that are older than a day?

I’m using Amazon Linux with bash shell. I wanted to delete all directories and files more than a day old in a certain directory, so I tried running this statement

sudo find /usr/java/jboss-as-7.1.3.Final/standalone/tmp/vfs -name "*" -type f -mmin +1441 -delete


However, immediately after running the above, when I check the directory, there are still child directories that are older than a day …

[mike@mymachine /]$ ls -al /usr/java/jboss-as-7.1.3.Final/standalone/tmp/vfs
total 240
drwxr-xr-x 17 jboss jboss 4096 Sep 20 23:24 .
drwxr-xr-x 5 jboss jboss 4096 Jun 24 2013 ..
drwxr-xr-x 186 jboss jboss 24576 Sep 20 21:12 deployment2368807199465dba
drwxr-xr-x 93 jboss jboss 20480 Sep 20 23:23 deployment2617ff35c8bff41a
drwxr-xr-x 6 jboss jboss 24576 Sep 19 20:26 deployment3571c00385713fe3
drwxr-xr-x 2 jboss jboss 20480 Sep 19 17:39 deployment3d351ede58f283dd
drwxr-xr-x 2 jboss jboss 20480 Sep 19 15:25 deployment4290f5e8ea8315f2
drwxr-xr-x 297 jboss jboss 24576 Sep 22 03:30 deployment9b31473d9eac9da0
drwxr-xr-x 2 jboss jboss 24576 Sep 20 18:56 deploymentceee45a133e7107d
drwxr-xr-x 93 jboss jboss 20480 Sep 19 18:55 deploymentefd5fbdbb2c4c444
drwxr-xr-x 2 jboss jboss 4096 Sep 20 18:57 temp165d12bb32054951
drwxr-xr-x 2 jboss jboss 4096 Sep 19 17:40 temp32dd5d98d5a4b497
drwxr-xr-x 2 jboss jboss 4096 Sep 19 15:26 temp59d119fda3e5ddc4
drwxr-xr-x 2 jboss jboss 4096 Sep 19 20:27 temp7f6ba3704ffeea57
drwxr-xr-x 2 jboss jboss 4096 Sep 20 23:23 temp861658110cf44173
drwxr-xr-x 2 jboss jboss 4096 Sep 19 18:56 tempcdad4bb17e60cb75
drwxr-xr-x 2 jboss jboss 4096 Sep 20 21:13 tempe1ee5a5f7f5c7636


What is the right way to write a statement that will delete everything in a certain directory that is older than a day?

Edit: Hey you’re suggestion didn’t work. I got this error

[mike@mymachine ~]$ sudo find /usr/java/jboss/standalone/tmp/vfs/ -mindepth 1 -mtime +1 -delete
find: cannot delete `/usr/java/jboss/standalone/tmp/vfs/deploymentefd5fbdbb2c4c444': Directory not empty
find: cannot delete `/usr/java/jboss/standalone/tmp/vfs/deployment3571c00385713fe3': Directory not empty

Answer

Try using the '-exec' option instead of '-delete', then you can add any command you want on each file, including a very scary 'rm -rf'.

For example, to call 'echo -n' on every file older than a day, run the following. Note '{}' is a placeholder for the found file/directory.

sudo find /usr/java/jboss-as-7.1.3.Final/standalone/tmp/vfs -mindepth 1 -mmin +1441 -exec echo -n {} \;

Edited to include '-mindepth 1', otherwise root search directory is included in results.

So, to recursively delete everything older than 1 day in the specified directory:

sudo find /usr/java/jboss-as-7.1.3.Final/standalone/tmp/vfs -mindepth 1 -mmin +1441 -exec rm -rf {} \;