繁体   English   中英

使用bash命令计算文件夹大小而不使用du左右

[英]Calculating folder size using bash commands without using du or so

我想知道是否有某种方法可以仅使用没有 du 的基本 Bash 命令来计算文件夹大小。 它适用于非常有限的环境(如救援模式),没有像 du 这样的实用程序。 先感谢您!

理论上,您可以仅使用 bash 内置函数来计算文件夹的大小。 但是,我怀疑这样的命令是否有真正的用例。 即使在救援模式下,您也应该能够运行du 也许您只需要指定完整路径:尝试/bin/du/usr/bin/du 即使这不起作用,您可能还有其他命令(例如stat或至少ls )可用于有效获取单个文件的大小,该文件可用于编写简单的脚本。

无论如何,让我们递归地总结当前/给定目录中所有(可读)文件的表观大小......

...仅使用 bash 内置函数:

(不要在现实生活中使用它)

#! /bin/bash
dir=${1-.}

LC_ALL=C
shopt -s globstar nullglob

declare -i size
add() { records+=1; size+=${#2}+1; MAPFILE=(); }
filesize() {
  declare -i records=0
  mapfile -d '' -c 1 -C add < "$1"
  # computed size is correct iff
  # file is empty or ends with a null byte,
  # otherwise the size is off by +1.
  # heuristic to correct this:
  (( size -= records > 0 ))
}

for file in "$dir"/**; do
  [[ -f "$file" && -r "$file" && ! -L "$file" ]] || continue
  filesize "$file"
done
echo "$size $dir"

如果我们有像cat这样的命令,我们可以使用mapfile ... <(cat "$1"; printf .); ((size--))修复filesize()的 +/-1 问题mapfile ... <(cat "$1"; printf .); ((size--)) mapfile ... <(cat "$1"; printf .); ((size--)) ; 但据我所知,仅使用 bash 内置程序无法打印文件的确切内容。

上面的命令基本上是du --appaparent-size -sb但不包含不可读的文件,但包含多次指向同一文件的多个硬链接。
此外,它是超级慢。 在带有由head -c 100M /dev/urandom生成的文件的测试目录中,脚本花费了两分钟多的时间!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM