Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 磁碟空間清理實戰:大檔案定位、日誌清空、批次刪除與目錄大小排序

編輯:Linux 教學

伺服器磁碟告警時,需快速定位佔用空間的大檔案/目錄並安全清理。本文提供從發現到清理的標準化指令工具箱。

1. 定位大檔案(指定目錄、大小閾值)


# 找出 /data 目錄下超過 100MB 的檔案,顯示詳細資訊
find /data -type f -size +100M -exec ls -lh {} \;

# 找出全系統超過 500MB 的檔案(排除 /proc、/sys、/dev)
find / -type f -size +500M -not -path "/proc/*" -not -path "/sys/*" -not -path "/dev/*" -exec ls -lh {} \;

2. 目錄大小排序(找出佔用最大的目錄)


# 當前目錄下一級子目錄大小,按人類可讀格式倒序顯示前 10
du -h --max-depth=1 | sort -hr | head -10

# 僅顯示前 5 大目錄(數值排序,單位 MB)
du -m --max-depth=1 | sort -nr | head -5

3. 安全清空日誌/文字檔(保留檔案、inode、權限)


# 清空單一檔案
> /var/log/nginx/access.log
# 或
: > /var/log/nginx/access.log
# 或
truncate -s 0 /var/log/nginx/access.log

# 批次清空某目錄下所有 .log
find /var/log -name "*.log" -exec truncate -s 0 {} \;

原理:截斷檔案大小為 0,釋放資料塊,但檔案描述符、inode、權限保持不變,寫入進程無感知,避免需重啟服務。

4. 直接刪除超大檔案(謹慎,確認無進程持有)


# 刪除 /var/mail 下超過 50MB 的檔案
find /var/mail -type f -size +50M -exec rm -f {} \;

# 刪除前先確認無進程開啟(lsof)
lsof /var/mail/large_file.mail
# 若有進程持有,需先停止服務或用 `> file` 清空而非刪除

5. 釋放已刪除但被進程持有的空間

現象:df -h 顯示磁碟滿,但 du -sh / 顯示佔用少,差值即為「已刪除開啟檔案」佔用的塊。


# 找出持有已刪除檔案的進程
lsof -nP | grep '(deleted)'

# 例:發現 pid 1234 持有 /var/log/messages (deleted)
# 方案一:優雅重啟該服務(systemctl reload rsyslog)
# 方案二:強制釋放(僅限無法重啟時)
#   進入 /proc/1234/fd/,找到對應 fd,執行 > /proc/1234/fd/N

6. 定期清理自動化(logrotate + cron)


# /etc/logrotate.d/custom-app
/var/log/myapp/*.log {
    daily
    rotate 7
    compress
    delaycompress
    missingok
    notifempty
    create 640 www www
    sharedscripts
    postrotate
        systemctl reload myapp > /dev/null 2>&1 || true
    endscript
}

指令速查卡

需求指令
找大檔find /path -type f -size +100M -exec ls -lh {} \;
目錄大小排序du -h --max-depth=1 | sort -hr
清空檔案> file / truncate -s 0 file
刪除大檔find /path -type f -size +50M -delete
查已刪未釋放lsof -nP | grep deleted
Copyright © Windows教程網 All Rights Reserved