Linux系统清理旧内核的完整指南
旧内核积累会占用/boot分区空间、导致GRUB菜单冗长,甚至影响系统启动速度。以下是针对不同发行版的清理方法及注意事项:
uname -r,输出结果即为系统当前加载的内核版本(如6.8.4-060804-generic)。务必保留当前内核,避免删除后无法启动。dpkg --list | grep linux-image(显示ii标记的为已安装内核);rpm -qa | grep kernel(列出所有内核包);dnf list installed | grep kernel;zypper search -i kernel。ls /boot | grep <内核版本>(如5.15.0-107),若存在vmlinuz-xxx(内核镜像)、initrd.img-xxx(初始内存盘)等文件,需手动清理(见下文“手动清理残留”步骤)。sudo apt autoremove --purge,该命令会自动移除不再需要的依赖包(包括旧内核)及配置文件,是最安全的方式。5.4.0-110-generic):sudo apt purge linux-image-5.4.0-110-generic linux-headers-5.4.0-110-generic
sudo apt autoremove --purge # 清理残留依赖
sudo yum remove kernel-<旧版本号>(如kernel-3.10.0-1160.el7.x86_64),或使用--oldinstallonly参数自动清理旧内核(保留最新2个):sudo yum -y remove --oldinstallonly --setopt installonly_limit=2 kernel
sudo yum clean all # 清理YUM缓存
sudo dnf autoremove --assumeyes自动清理,或手动删除:sudo dnf remove kernel-<旧版本号>
sudo dnf autoremove
方法与CentOS 8+类似,优先使用dnf autoremove自动清理,或手动指定内核版本删除。
运行zypper search -i kernel列出已安装内核,然后执行:
sudo zypper remove <旧版本号>
sudo zypper autoremove
若autoremove未完全清理/boot目录中的残留文件(如vmlinuz-xxx、initrd.img-xxx),可手动删除:
sudo rm /boot/vmlinuz-<旧版本号> # 删除内核镜像
sudo rm /boot/initrd.img-<旧版本号> # 删除初始内存盘
删除后需更新GRUB配置(见下文)。
清理旧内核后,需重新生成GRUB菜单以移除旧版本选项:
sudo update-grub;sudo grub2-mkconfig -o /boot/grub2/grub.cfg。uname -r显示的版本是系统运行的基础,删除会导致无法启动。df -h /boot,确保剩余空间大于200MB(避免系统无法安装新内核)。/boot目录(如sudo tar -czf /backup/boot_backup.tar.gz /boot),以防误删。通过以上步骤,可安全清理旧内核,释放磁盘空间并保持系统整洁。建议每3-6个月执行一次,或在升级内核后及时清理旧版本。