【问题标题】:Strange behavoir with find and dufind 和 du 的奇怪行为
【发布时间】:2020-02-02 01:03:06
【问题描述】:

我正在尝试在 shell 脚本的某些文件夹中生成用户使用情况,但我发现我的 find 和 du 组合出现了一些奇怪的行为。

我有一个包含约 9500 个文件的文件夹,总共 5GB。此文件夹的 4GB 由 7 个大文件组成,其余 1GB 由小文件组成(其中近 9000 个)。我遇到的问题是我的脚本似乎忽略了大部分文件,因此 du 报告的总使用量不正确。

下面的行给出了文件总数的正确数字(总数+1):

$ find . -type -f -exec du -ch {} + | wc -l
9596

但是,如果我只是尝试获取它返回的所有文件的总数和不正确的值。

$ find . -type -f -exec du -ch {} + 
...lines of files
139M total < this value is incorrect, should be ~5GB

如果我将大小限制为大文件(超过 25MB),它确实会拾取大文件并靠近,但显然缺少构成剩余 1GB 的许多小文件。

$ find . -type -f -size +25M -exec du -ch {} + 
561M    ./largefile0
483M    ./largefile1
514M    ./largefile2
948M    ./largefile3
360M    ./largefile4
768M    ./largefile5
764M    ./largefile6
4.3G    total < this is the correct total for these files

最后,更奇怪的是,如果我在没有 size 参数的情况下再次运行该命令,然后 grep for large 它会选择 largefile[0-6] 文件。

$ find . -type -f -size +25M -exec du -ch {} + | grep large
561M    ./largefile0
483M    ./largefile1
514M    ./largefile2
948M    ./largefile3
360M    ./largefile4
768M    ./largefile5
764M    ./largefile6

所以我不太确定这里发生了什么,好像 du 可以报告的文件数量是其总数的限制,但对于这个数据集来说,它似乎总是等于 139M。

【问题讨论】:

    标签: bash find du


    【解决方案1】:

    不清楚你在问什么。如果只是对结果的解释,那么:

    -exec {} + 谓词不会只执行一次,它有一个大小限制,当达到该大小限制时,将执行命令并开始组合新的“命令”,请参阅:https://git.savannah.gnu.org/cgit/findutils.git/tree/find/exec.c#n153

    在我的机器上,大小约为 128K。

    $ find ./ -type f -name 'file*' -exec echo {} + 2>/dev/null | head -1 | wc -c
    131056
    

    对于一个包含大约 40000 个文件的示例目录,该命令会执行 7 次。

    $ find ./ -type f -name 'file*' -exec echo {} + | wc -l
    7
    

    如果我限制文件的数量,它适合一个:

    $ find ./ -type f -name 'file5*' -exec echo {} + | wc -l
    1
    

    如果你想得到文件大小的最终总和:

    find ./ -type f -name 'file*' -exec du -ck {} + | awk ' $2 == "total" { T+=$1 } END { print T } '
    

    请注意,我使用k 而不是h 以确保所有结果的数量级相同。

    【讨论】:

    • 抱歉,我问你的问题成功地为我解码和回答!我设法用您的输入调整了我的脚本,它现在可以工作了。在我的测试目录中,我看到该命令需要执行两次。对“总”的搜索使其弹出!
    猜你喜欢
    • 2013-09-27
    • 1970-01-01
    • 2015-01-11
    • 2020-03-09
    • 1970-01-01
    • 2015-09-06
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多