如何查找在过去 24 小时内修改过的文件,但不从隐藏目录中找到文件并对它们求和

How to find files modified in last 24 hr but do not find from hidden directories and sum them

我有以下命令来查找在过去 24 小时内修改过的文件并对所有文件求和。

#!/bin/bash

find /mnt/naspath -mtime 0 -print0 | du --files0-from=- -hc | tail -n1 >> /tmp/size.log
exit 0

但是它也会对 .snapshot

下的隐藏目录中的文件求和

我在查找手册页中看到的是我可以排除 .snapshot 以及我不太清楚的内容。

#!/bin/bash

find . -name .snapshot -prune -o \( \! -name *~ -print0 \)

所以现在我希望用下面的命令排除隐藏和修改的文件,但这是完全相反的。它排除了 .snapshot 但总结了所有其他内容。 -mtime 0 未受影响。

#!/bin/bash

find /mnt/naspath -mtime 0  -name .snapshot -prune -o \( \! -name *~ -print0 \) | du --files0-from=- -hc | tail -n1 >> /tmp/size.log

exit0

任何人都知道如何更正命令。 谢谢

解决方案

有两种写法:

  1. 喜欢4ae1e1上面的评论

    find /mnt/naspath -name .snapshot -prune -o \( -type f -mtime 0 -print0 \)
    

    换言之:

    If name is '.snapshot' then prune, otherwise if type is file and modified in last 24 hrs, then -print0

  2. 或者

    find /mnt/naspath \! \(-name .snapshot -prune\) -type f -mtime 0 -print0
    

    换言之:

    If not pruned (in case name was '.snapshot') and type is file and modified in last 24hrs, then -print0

分析

好了,明白了,你第二次尝试哪里出了问题,我们再看一下

find /mnt/naspath -mtime 0  -name .snapshot -prune -o \( \! -name *~ -print0 \)

首先,我们按照 find 对其进行解释的方式对其进行扩展(即插入隐式 -ands 并遵守运算符优先级 (...) > \! > -and > -or).这导致:

find /mnt/naspath \( \
        \( -mtime 0 -and -name .snapshot \) -and -prune \
    \) -or \( \
        \( \! -name *~ \) -and -print0 \
    \)

\只用于转义。这现在更容易理解了——换句话说:

Any path matching -mtime 0 -and -name .snapshot will be pruned (i.e. skipped and not be descendet into, in case of a directory). For everything else which does not match -name *~ do -print0.

显然这与您的意图不符,因为您只想修剪名为 .snapshot independent 的路径的修改时间。这种不同结果的主要原因是 -prune 命令的位置和运算符优先级规则。相反,过滤器 -mtime 0 应该应用于所有未修剪的内容。最后但并非最不重要的一点是,过滤器 \! -name *~ 不会做任何你想做的事情,相反你需要一个额外的过滤器 -type f 来从最终计数中排除目录。

备注

注意:表达式-name .snapshot -prune应该是第一个要执行的表达式。

例如 -type f \! \(-name .snapshot -prune\) 而不是 \! \(-name .snapshot -prune\) -type f 会导致名为 .snapshot 的非文件出现不同的行为,例如您的目录。一旦 -type f 的计算结果为 false,find 将停止计算下一个表达式(因为它 隐式 链接到 -and,这永远不会为真)。两种情况的最终结果都是假的,但是第一种情况下不会执行 prune,这意味着后续的后代 into '.snapshot' 不会被阻止。

PS:我希望这个解释对您的问题有所帮助。如果您喜欢这个答案,请不要忘记投票。 :-)