檔案系統隨時間累積大量雜項,定期清理是維運基本功。同時,測試指令時常需「乾淨環境」排除變數干擾。本文結合 find 統計分析與 env -i 環境隔離,提供實戰可用的清理與除錯技巧。
find /path -type f | wc -l
# 含隱藏檔、遞迴子目錄
# 最舊(依修改時間 mtime)
find /path -type f -printf '%T+ %p\n' | sort | head -n 1
# 最新
find /path -type f -printf '%T+ %p\n' | sort | tail -n 1
# 忽略隱藏檔/目錄
find /path -type f -not -path '*/.*' -printf '%T+ %p\n' | sort | tail -n 1
find /path -type f -printf '%s %p\n' | sort -rn | head -n 20
# %s = 大小(bytes), %p = 完整路徑
find /path -type f -printf '%u\n' | sort | uniq -c | sort -rn
# 最久未存取
find /path -type f -printf '%A+ %p\n' | sort | head -n 1
# 最近存取
find /path -type f -printf '%A+ %p\n' | sort | tail -n 1
# 找出 2 年內未存取的大檔(清理候選)
find /path -type f -atime +730 -size +100M -printf '%A+ %s %p\n' | sort
#!/bin/bash
TARGET="${1:-.}"
echo "=== File System Report for $TARGET ==="
echo "Total files: $(find "$TARGET" -type f | wc -l)"
echo "Oldest: $(find "$TARGET" -type f -printf '%T+ %p\n' | sort | head -1)"
echo "Newest: $(find "$TARGET" -type f -printf '%T+ %p\n' | sort | tail -1)"
echo "Largest: $(find "$TARGET" -type f -printf '%s %p\n' | sort -rn | head -1)"
echo "Owner distribution:"
find "$TARGET" -type f -printf '%u\n' | sort | uniq -c | sort -rn
echo "=== End ==="
env | wc -l
printenv | wc -l
# 完全忽略繼承的環境變數
env -i /usr/bin/wget https://example.com
# 等價寫法(bash/ksh/zsh)
env -i wget https://example.com
| 場景 | 問題 | env -i 解法 |
|---|---|---|
| 測試網路連線 | http_proxy 導致走代理 | env -i curl -I https://example.com |
| 比對編譯結果 | CC、CFLAGS、PATH 干擾 | env -i PATH=/usr/bin make |
| 驗證腳本不依賴環境 | 隱性依賴 HOME、LANG 等 | env -i ./myscript.sh |
| 排除 locale 影響 | 排序、日期格式差異 | env -i LANG=C LC_ALL=C sort file |
env -i 清除所有繼承變數,含 PATH,指令需用絕對路徑或手動重設 PATH。env -i bash -c 'env | wc -l' 會顯示 bash 內建變數。VAR=value command 或 env VAR=value command。
env http_proxy="https://user:pass@proxy:3128" https_proxy="https://user:pass@proxy:3128" \
wget https://example.com/large.iso
find /data -type f \
-mtime +90 \
-size +500M \
! -user root \
-printf 'Deleting: %p (%s bytes)\n' \
-delete
安全原則:
-printf 預覽,確認名單。tar、rsync)。-ok 互動確認,或寫入日誌後再 -delete。/etc, /boot, /usr, /lib)嚴禁 直接 find -delete。