如果你想知道当前目录中的内容占用了多少空间,你可以使用类似下面的代码
let TotalBytes=0 for Bytes in $(ls -l | grep "^-" | awk '{ print $5 }') do let TotalBytes=$TotalBytes+$Bytes done # The if...fi's give a more specific output in byte, kilobyte, megabyte, # and gigabyte if [ $TotalBytes -lt 1024 ]; then TotalSize=$(echo -e "scale=3 \n$TotalBytes \nquit" | bc) suffix="b" elif [ $TotalBytes -lt 1048576 ]; then TotalSize=$(echo -e "scale=3 \n$TotalBytes/1024 \nquit" | bc) suffix="kb" elif [ $TotalBytes -lt 1073741824 ]; then TotalSize=$(echo -e "scale=3 \n$TotalBytes/1048576 \nquit" | bc) suffix="Mb" else TotalSize=$(echo -e "scale=3 \n$TotalBytes/1073741824 \nquit" | bc) suffix="Gb" fi echo -n "${TotalSize}${suffix}" |
代码由我和 Sam Schmit 提供 (<id at pt dot lu>),以及 Sam 的叔叔 Jean-Paul,他修正了我原始代码中的一个相当大的 bug,并且总的来说,清理了它。
注意,你也可以直接使用ls -l | grep ^total | awk '{ print $2 }'因为ls -l会在开头输出一行,表示目录的大概大小,单位是 KB - 虽然由于我不清楚的原因,它似乎不如上面的脚本准确(但显然速度更快)。
相对速度:在 /usr/bin/ (目录大小为 14.7 MB) 中,在一个未加载的 486SX25 上,这个过程需要 3.2 到 5.8 秒,这取决于缓存了多少信息 (如果你在提示符中使用它,缓存多还是少取决于你在该目录中工作的时间长短)。