So, I've been able to figure out bits of this myself but am having trouble piecing them together. I have a task I need to automate - I have folders filled with gigabytes of obsolete files, and I want to purge them if they meet two criteria.
- Files must not have been modified in the past 14 days - for this, I'm using find -
find /dir/* -type f -mtime +14
- And the files cannot be in use, which can be determined by
lsof /dir/*
I don't know bash quite well enough yet to figure out how to combine these commands. Help would be appreciated. I think I essentially want to loop through each line of output from find, check if it is present in output from lsof, and if not, rm -f -- however, I am open to alternative methodologies if they accomplish the goal!
do lsof $x >/dev/null
- this is basically the unix way of saying if it's in use, do nothing by sending output to /dev/null - and if not, do this other command (in my case,rm -f
) – tastyCIDR Nov 14 '15 at 15:59lsof
to select between command 1 and command 2. The output oflsof
would only clutter the output of the for-loop, so that's why I redirect it to the 'sink'. – NZD Nov 14 '15 at 19:52lsof
on a file and the file is in use, its exit code is zero. You can check this by running commandecho $?
immediately after thelsof
command. That will print the exit code of the previous command. If the file is not in use, its exit code is one. You can again check this by running commandecho $?
immediately after thelsof
command. – NZD Nov 14 '15 at 19:56Thanks!
– tastyCIDR Nov 15 '15 at 06:18$x
with"$x"
it will handle file names with spaces and on my system (Ubuntu 14.04) also with?
and*
in file names. It treats?
and*
as normal characters. – NZD Nov 15 '15 at 21:07