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

Ubuntu 清理舊核心完整指南:釋放 /boot 空間與縮短開機選單

編輯:Linux 教學

前言

Ubuntu 透過自動更新頻繁安裝新核心,舊核心不會自動移除,導致 /boot 分區空間不足、GRUB 選單冗長。本文說明如何列出已安裝核心、識別當前使用核心、安全移除舊核心並更新開機載入器。

一、列出所有已安裝核心套件

dpkg --get-selections | grep linux-image

輸出範例:

linux-image-5.15.0-46-generic    install
linux-image-5.15.0-48-generic    install
linux-image-5.15.0-50-generic    install
linux-image-generic              install
  • linux-image-x.x.x-xx-generic:具體核心版本
  • linux-image-generic:元套件,永遠指向最新核心

二、確認當前正在使用的核心

uname -r
# 輸出範例:5.15.0-50-generic

絕對不要移除此版本對應的套件!

三、移除舊核心套件

方法 1:手動指定版本移除 (推薦新手)

# 僅移除核心映像
sudo apt-get remove linux-image-5.15.0-46-generic

# 連同 headers、modules 一併移除 (更乾淨)
sudo apt-get remove linux-image-5.15.0-46-generic linux-headers-5.15.0-46-generic linux-modules-5.15.0-46-generic linux-modules-extra-5.15.0-46-generic

方法 2:一次移除所有非當前核心 (進階)

# 列出所有非當前核心的 image 套件
dpkg -l 'linux-image-*' | awk '/^ii/ && $2 !~ "'"$(uname -r)"'" {print $2}' | xargs sudo apt-get -y purge

執行前請三次確認列表不含當前核心!

方法 3:使用 apt autoremove (Ubuntu 18.04+ 自動保留當前及前一版)

sudo apt autoremove --purge

此指令會自動移除不再需要的舊核心、孤立套件,保留當前運行核心及其前一版作為回滾備用。

四、清理後驗證

# 檢查 /boot 空間
df -h /boot

# 確認 GRUB 選單已更新
grep menuentry /boot/grub/grub.cfg

# 重開機測試
reboot

五、常見問題與注意事項

問題說明
/boot 100% 滿導致 apt 無法安裝新核心先手動刪除 /boot 下最舊的 vmlinuz/initrd 檔案騰出空間,再執行 apt-get -f install
誤刪當前核心系統下次重開機將無法啟動,需用 Live USB 掛載根分區重裝核心套件
保留幾個舊核心較安全?建議保留當前 + 前一版 (共 2 個),兼顧空間與回滾能力
HWE (Hardware Enablement) 核心LTS 版本可能有 linux-image-5.13.0-xx-generic (HWE) 與 linux-image-5.4.0-xx-generic (GA) 並存,分別管理

六、自動化腳本範例 (放入 cron 定期執行)

#!/bin/bash
# 清理舊核心,保留當前與前一版
CURRENT=$(uname -r | sed 's/-generic//')
PREVIOUS=$(dpkg -l 'linux-image-*' | awk '/^ii/ {print $2}' | grep -v "$CURRENT" | tail -1 | sed 's/linux-image-//' | sed 's/-generic//')
apt-get -y purge $(dpkg -l 'linux-image-*' | awk '/^ii/ && $2 !~ "linux-image-('"$CURRENT"'|'"$PREVIOUS"')" {print $2}')
apt-get -y autoremove
update-grub

總結

定期清理舊核心是 Ubuntu 維護的基本功。掌握 dpkg --get-selections、uname -r、apt remove/purge、apt autoremove 組合拳,即可輕鬆控制 /boot 空間與 GRUB 選單長度。

Copyright © Windows教程網 All Rights Reserved