简体   繁体   English

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

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

I wonder if there is some way to calculate folder size using only basic Bash commands without du.我想知道是否有某种方法可以仅使用没有 du 的基本 Bash 命令来计算文件夹大小。 It is for very limited evironment (like rescue mode) that has no such utilities as du.它适用于非常有限的环境(如救援模式),没有像 du 这样的实用程序。 Thank you in advance!先感谢您!

Theoretically, you can calculate the size of a folder using only bash built-ins.理论上,您可以仅使用 bash 内置函数来计算文件夹的大小。 However, I doubt there is a real use-case for such a command.但是,我怀疑这样的命令是否有真正的用例。 Even in rescue mode you should be able to run du ;即使在救援模式下,您也应该能够运行du maybe you just have to specify the full path: Try /bin/du or /usr/bin/du .也许您只需要指定完整路径:尝试/bin/du/usr/bin/du Even if that did not work you probably have other commands (eg stat or at least ls ) which could be used to efficiently get the size of a single file, which could be used to write a simple script.即使这不起作用,您可能还有其他命令(例如stat或至少ls )可用于有效获取单个文件的大小,该文件可用于编写简单的脚本。

Anyways, lets sum up the apparent sizes of all (readable) files in the current/given directory recursively …无论如何,让我们递归地总结当前/给定目录中所有(可读)文件的表观大小......

… using only bash built-ins: ...仅使用 bash 内置函数:

(Don't use this in real live) (不要在现实生活中使用它)

#! /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"

If we had a command like cat we could fix the +/-1 problem in filesize() using mapfile ... <(cat "$1"; printf .); ((size--))如果我们有像cat这样的命令,我们可以使用mapfile ... <(cat "$1"; printf .); ((size--))修复filesize()的 +/-1 问题mapfile ... <(cat "$1"; printf .); ((size--)) mapfile ... <(cat "$1"; printf .); ((size--)) ; mapfile ... <(cat "$1"; printf .); ((size--)) ; but as far as I know there is no way to print the exact content of a file using only bash built-ins.但据我所知,仅使用 bash 内置程序无法打印文件的确切内容。

Above command is basically du --appaparent-size -sb but does not include unreadable files but includes multiple hardlinks to the same file multiple times.上面的命令基本上是du --appaparent-size -sb但不包含不可读的文件,但包含多次指向同一文件的多个硬链接。
Also, it is super slow.此外,它是超级慢。 On a test directory with a file generated by head -c 100M /dev/urandom the script took more than two minutes!在带有由head -c 100M /dev/urandom生成的文件的测试目录中,脚本花费了两分钟多的时间!

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

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