Hello,
How would I write a BASH script to remove all sub directories in a root level directory that are older than
10 days, but exclude directories owned by certain users. I would need to run as a cron job once a week.
Thank you
-John
Hello,
How would I write a BASH script to remove all sub directories in a root level directory that are older than
10 days, but exclude directories owned by certain users. I would need to run as a cron job once a week.
Thank you
-John
What code do you have now?
An overview of the steps:
cd to the directory
use find to locate directories with mtime > 10 days, rm -r the sub directory
One caveat - if you have multiple directory levels you may want to rethink your design. BY this I mean,
dira
dirb
dirx
dirc
dirm
dirn
if you clobber dirc
because it has not been written to, and dirn
is still being modified you have a problem.
find /path/to/directory -type d ! \( -user user1 -o -user user2 \) ! -ctime -10 -print
find
: find command to recursively locate files, links and directories.
/path/to/directory
: location where to start searching from.
-type d
: return true if is a directory.
! \( -user user1 -o -user user2 \)
: returns true if it DOES NOT belong to user1 or user2.
! -ctime -10
: returns true if is NOT less than 10 days old.
-print
: display the result. It is the default and can be omitted. But here is a place holder for following explanation.
If you like what you get, change the -print
for -exec rm -rf {} +
which, recursively, will delete those directories that matched.
There is an implied AND between all these expressions, which means: if is a directory AND if it doesn't belong to user1 or user2 AND if is not younger than 10 day.
If you want to exclude more users just add a -o -user <username>
inside the ! \( \)
The ! -ctime -10
can be changed to -ctime +10
as well