argument list too long: rm 檔案過多,無法直接使用rm清除時的解決方法

工作時遇到有人設定排程更新服務時,使用了wget定時觸發特定連結並把檔案寫入特定目錄中,造成硬碟滿載無法上傳檔案。

經過調查後發現其實連結本身並不會回傳資料,所以記錄下來的檔案本身並沒有任何作用,但是因為檔案數量過多,造成硬碟滿載。

即使是空檔案,也會佔用一個固定的容量,至於是多少則取決於你分割硬碟時設定的Block size

當下直覺的使用rm run.*試著移除,結果跳出argument list too long: rm

以下附上可以解決的幾種方法


# 使用xargs幫你減少一次餵給rm的數量
ls | xargs -n1000 rm

# 使用find幫你直接刪除
find ./ -name 'run.*' -delete

# 當你檔案實在太多,多到會讓你可以去外面沖杯咖啡再回來時可以用這個
find ./ -name 'run.*'  -printf 'rm %f \n' -delete

Benchmark

使用touch test.{1..100000}產生十萬筆空檔案,並用time計時。

time ls | xargs  -n1000 rm # 2.279 s
ls --color=tty  0.27s user 0.05s system 28% cpu 1.106 total
xargs -n1000 rm  0.11s user 0.79s system 76% cpu 1.173 total

time find . -name 'test.*' -delete # 0.753 s
find . -name 'test.*' -delete  0.11s user 0.63s system 98% cpu 0.753 total

同場加映

curl是你的救星,你可以選擇不要在伺服器裡埋下未爆彈。

* * * * * root curl https://cron.404nofound.com/cron/run

我只想用wget怎麼辦

* * * * * root wget -O - -o /dev/null https://cron.404nofound.com/cron/run

或者你可以多去看看你用的框架給的官方文件,不要寫出這種莫名其妙的東西。


其他相關