![使用 du 以位元組和人類可讀格式遞歸列出目前目錄中前 20 個最大資料夾/檔案的大小](https://rvso.com/image/154457/%E4%BD%BF%E7%94%A8%20du%20%E4%BB%A5%E4%BD%8D%E5%85%83%E7%B5%84%E5%92%8C%E4%BA%BA%E9%A1%9E%E5%8F%AF%E8%AE%80%E6%A0%BC%E5%BC%8F%E9%81%9E%E6%AD%B8%E5%88%97%E5%87%BA%E7%9B%AE%E5%89%8D%E7%9B%AE%E9%8C%84%E4%B8%AD%E5%89%8D%2020%20%E5%80%8B%E6%9C%80%E5%A4%A7%E8%B3%87%E6%96%99%E5%A4%BE%2F%E6%AA%94%E6%A1%88%E7%9A%84%E5%A4%A7%E5%B0%8F%20.png)
需要實現的幾件事 1. 遞歸獲取前 20 個最大的資料夾/檔案 2. 取得它們的大小(以位元組為單位)以及人類可讀的格式
答案1
#!/bin/bash
# ------------------------------------------
# Copy paste this content in a bash script e.g. ducks.sh
# And use it directly.
# ------------------------------------------
# Refer:
# https://www.cyberciti.biz/faq/linux-find-largest-file-in-directory-recursively-using-find-du/
# https://unix.stackexchange.com/a/220470/353485
function bytesToHR() {
local SIZE=$1
local UNITS="B KiB MiB GiB TiB PiB"
for F in $UNITS; do
local UNIT=$F
test ${SIZE%.*} -lt 1024 && break;
SIZE=$(echo "$SIZE / 1024" | bc -l)
done
if [ "$UNIT" == "B" ]; then
printf "%4.0f %s\n" $SIZE $UNIT
else
printf "%7.02f %s\n" $SIZE $UNIT
fi
}
du --block-size=1 --all ./ | sort -rn | head -n 20 > ./dump.txt
ALL_SIZES="`awk '{print $1}' ./dump.txt`"
# echo $ALL_SIZES
rm -f ./new_dump.txt
for s in $ALL_SIZES; do
bytesToHR $s >> ./new_dump.txt
done
paste ./new_dump.txt ./dump.txt