1

Below is a simple script that searches for files older than 30 days, then returns the number of files, or ZERO.

I'd like it to do the following, if possible:

  • exit from the loop if it finds anything older than 30 days, and moves to the next line in list.dat

This way, it won't have to recurse further through someone's directory since we've found what we're looking for, as some of these directories are huge and we're using an aging SAN so it's glacial.

We're basically trying to generate a report of 'home' folders that have been idle for more than 30 days, but cannot extract this info via any other way than this.

I don't believe there is any way to capture the exit status of 'find' to make this any easier...

Or, if anyone has a suggestion on how to do this differently, I'm all ears.

Any suggestions, ideas or help much appreciated!

Dan

#!/bin/sh
PATH=/bin:/usr/bin:/usr/sbin export PATH
SOURCEDIR=/Volumes/UserHomes/

while IFS= read -r line

do

  COUNT=$(find $SOURCEDIR/$line -type f -mtime -30 | wc -l)
  if [ "$COUNT" -eq 0 ]; then
     echo $line ZERO
  else
     echo $line $COUNT files found
  fi

done < $SRCLIST
4

2 回答 2

4

尝试在命令行中添加-quit选项;find一旦找到第一个匹配的文件,它就会退出。您必须添加-print以确保打印找到的名称。

有了这个,你可以简化你的表达:

if [ -n  "$(find ${SOURCEDIR}/${line} ... -print -quit)" ] ; then
  echo "Something found in ${line}!"
fi

这是一个展示这个想法的最小概念验证示例。

# get us an empty dir
mkdir find-example
cd find-example

# create / freshen a few files
touch foo bar baz

# create a subdir with a matching file
mkdir -p nested
touch nested/quux

# finds four files:
find . -type f -mtime -30
# prints:
# ./foo
# ./nested/quux
# ./baz
# ./bar

# finds only one file and stops
find . -type f -mtime -30 -print -quit

# prints:
# ./foo
# and exits.

以上内容可在 GNU/Linux,特别是 Ubuntu 12.04 上重现。

我可以想象这find可能会分叉以加快并行扫描子目录的速度,并且-quit在其中一个中遇到其他搜索过程后可能会继续一段时间;man 1 find明确声明-quit结束所有子流程,但这可能不会立即发生。这只是我的猜测;我没有在大树上测试它,也没有看源码。之后我再也没有看到find继续递归下降-quit。我从未在 OSX 或 BSD + GNU findutils 上尝试过。YMMV。

于 2013-05-04T03:46:24.920 回答
1

如果您通过管道传输到 head -1 然后 wc -l 这应该会在您找到第一个文件后终止命令

COUNT=$(find $SOURCEDIR/$line -type f -mtime -30 | head -1 | wc -l)

如果文件在不到 30 天前被修改,这将返回计数 1

于 2013-05-04T03:53:25.737 回答