如何刪除舊未使用的Linux內核
Each installed Linux kernel occupies a significant amount of disk space. Over time, as you update your kernel to newer versions, older kernels can accumulate on your system, taking up valuable disk space. By removing old kernels, you can free up disk space, allowing for more efficient utilization and preventing potential storage shortages. In this guide, we will learn how to find and remove old unused Kernels in Linux operating systems.
DISCLAIMER: The following instructions for deleting old unused Linux kernels involve operations that can significantly affect your system. Incorrect usage of these commands can lead to system instability or data loss. It's strongly advised to:
- Backup your data: Always ensure that you have a current backup of your system and important files. This will allow you to restore your data if anything goes wrong.
- Keep old kernels: Always keep at least one or two old kernels. They serve as a fallback if the current version fails or encounters issues.
- Check the current kernel version: Be sure to check your current kernel version and ensure that it is not removed during this process.
- Understand the commands: Before running any command, make sure you understand what it does. If you're unsure about a command, let us know via the comment section below or seek advice from a knowledgeable source.
- Proceed with caution: If you're not comfortable performing these operations, seek assistance from a system administrator or a knowledgeable individual.
Remember, you bear the full responsibility for the results of following these instructions. Proceed with caution and at your own risk.
Table of Contents
Where Linux Kernels are Stored?
All installed Linux kernels and their associated files are typically stored under the /boot directory. And the Kernel modules are usually stored in /lib/modules directory.
The /boot directory contains the files related to the Linux kernel, including the kernel images, initramfs files, and bootloader configurations. The kernel files typically have names starting with "vmlinuz-" or "vmlinuz." and end with the version number.
The /lib/modules directory stores the kernel modules associated with each installed kernel. Kernel modules are dynamically loadable components that extend the functionality of the Linux kernel. Each kernel version has its own subdirectory within /lib/modules/.
By default, most recent Linux distributions retain the current Linux kernel version and one previous version for rescue purposes. This ensures that if any issues arise after upgrading to a new kernel version, you can easily boot into the older, known-working kernel.
However, there are instances where you might have manually installed Linux kernels or installed a specific Kernel from third-party repositories. In such cases, the older kernels will not be removed automatically when running package cleaning commands such as sudo apt autoremove.
Consequently, these older versions continue to accumulate in the /boot directory, gradually occupying more disk space over time. Therefore, it becomes necessary to identify and delete these old, unused Linux kernels to free up valuable disk space.
Remove Old Unused Kernels in Linux
Debian and its derivatives, along with RHEL and its variants, are among the most prevalent operating systems in use today. Therefore, we will delve into the process of removing Linux kernels specifically within these two categories of operating systems.
First, we will see how to remove old, unused Kernels in Debian-based systems.
1. Delete Old Unused Kernels in Debian, Ubuntu, Linux Mint
There are a few ways to delete old Kernels in Debian, Ubuntu and its derivatives such as elementary OS, Linux Mint, and Pop!_OS.
1.1. List Installed Linux Kernels
First, you need to verify the list of all installed Linux Kernels. To check all installed Kernels in Debian, Ubuntu and its derivatives, run:
$ dpkg --list | grep linux-image
Sample Output from my Ubuntu 22.04 system:
rc linux-image-5.15.0-25-generic 5.15.0-25.25 amd64 Signed kernel image generic rc linux-image-5.15.0-30-generic 5.15.0-30.31 amd64 Signed kernel image generic rc linux-image-5.15.0-39-generic 5.15.0-39.42 amd64 Signed kernel image generic ii linux-image-5.15.0-41-generic 5.15.0-41.44 amd64 Signed kernel image generic ii linux-image-5.19.0-42-generic 5.19.0-42.43~22.04.1 amd64 Signed kernel image generic ii linux-image-generic-hwe-22.04 5.19.0.42.43~22.04.15 amd64 Generic Linux kernel image
As you may noticed in the output, the first column displays "rc" and "ii". You might wonder what are those.
The "ii" and "rc" are package status indicators. Here's what they represent:
- "ii" stands for "installed, and successfully installed/configured." It indicates that the corresponding package is currently installed on your system and is in a functional state.
- "rc" stands for "removed, but the configuration files are still present." It indicates that the package has been removed, but its configuration files are still present on the system. This status is usually seen when a package is removed but not purged completely, keeping the configuration files for potential reinstallation in the future.
So, in the above output, the packages with "ii" status (linux-image-5.15.0-41-generic and linux-image-5.19.0-42-generic) are currently installed on my system. On the other hand, the packages with "rc" status (linux-image-5.15.0-25-generic, linux-image-5.15.0-30-generic, and linux-image-5.15.0-39-generic) have been removed, but their configuration files are still present.
Heads Up: The package status information provided here is specific to the output of the dpkg --list command, where the first column indicates the package status.
1.2. Remove Old, Unused Kernels Automatically
Now, let us delete old and unused Linux Kernels in Debian-based systems using the following command:
$ sudo apt-get autoremove --purge
The command sudo apt-get autoremove --purge is used to remove automatically installed packages that are no longer needed on your system, including their configuration files. Here's what each part of the command does:
- sudo: It executes the command with administrative privileges.
- apt-get: It is the package management command-line tool in Debian-based systems (such as Ubuntu) used for handling packages.
- autoremove: It is an apt-get sub-command that automatically removes packages that were installed as dependencies but are no longer required by any other package on your system.
- --purge: It is an option that, when used with autoremove, removes not only the package but also its associated configuration files. This ensures a more thorough cleanup.
When you run sudo apt-get autoremove --purge, the command scans your system for packages that were installed as dependencies but are no longer needed. It then removes those packages and their associated configuration files, freeing up disk space and cleaning up the system from unnecessary packages.
It is important to review the list of packages to be removed before confirming the command execution. This ensures that no critical packages are unintentionally removed.
Now let us check again the list of available Kernels with command:
$ <strong>dpkg --list | grep linux-image</strong> rc linux-image-5.15.0-25-generic 5.15.0-25.25 amd64 Signed kernel image generic rc linux-image-5.15.0-30-generic 5.15.0-30.31 amd64 Signed kernel image generic rc linux-image-5.15.0-39-generic 5.15.0-39.42 amd64 Signed kernel image generic ii linux-image-5.15.0-41-generic 5.15.0-41.44 amd64 Signed kernel image generic ii linux-image-5.19.0-42-generic 5.19.0-42.43~22.04.1 amd64 Signed kernel image generic ii linux-image-generic-hwe-22.04 5.19.0.42.43~22.04.15 amd64 Generic Linux kernel image
As I already said, the "rc" packages are removed but their configuration files are present in the system. Why the 'sudo apt autoremove' command didn't remove them? You might wonder.
The "rc" packages are not removed when you the "sudo apt autoremove --purge" command because the "autoremove" operation specifically targets packages that were installed as dependencies but are no longer needed by any other packages on your system.
The "rc" status indicates that the package has been removed but its configuration files are still present on the system. When you run "apt autoremove --purge", it only removes packages that are marked as "auto" or "orphans", meaning they were installed automatically as dependencies and are no longer required.
Since "rc" packages are not considered as dependencies and do not fall into the category of "auto" or "orphans", they are not automatically removed by the "apt autoremove" operation.
In this case, you can manually find and remove the unneeded Kernels as described in the following section.
1.3. Delete Unneeded Linux Kernels Manually
To remove old unused Linux kernels, you can follow these steps:
1. Check your current kernel version
Open a terminal and run the command:
$ uname -r
This will display the currently running kernel version. Make sure you don't remove this kernel.
2. List installed kernels
Run the following command to see the list of installed Linux kernels on your system.
$ dpkg --list | grep linux-image
3. Identify unused kernels
Review the list and identify the kernels you want to remove. Typically, you would want to keep the latest kernel and perhaps one or two previous versions as a backup.
4. Remove unused kernels
To remove a specific kernel, use the command:
$ sudo apt-get purge linux-image-x.x.x-x-generic
Where "x.x.x-x" represents the kernel version. Replace it with the actual version number you want to remove. Repeat this command for each kernel you want to uninstall.
4. Update the GRUB boot loader
After removing the old kernels, you should update the GRUB boot loader configuration to reflect the changes. Run the following command to update the boot loader.
$ sudo update-grub
5. Reboot your system
It's a good practice to reboot your system to ensure that everything is working correctly with the remaining kernel.
Please exercise caution when removing kernels, as removing the wrong kernel can render your system unbootable. Always double-check the version you want to remove and keep a backup kernel as a precaution.
Please note that we have only removed the unused old Kernels. There could be many unneeded package configuration files might still exist in the system. To remove them all, please follow the steps below.
1.4. Remove All Unnecessary Configuration Files
To remove all "rc" packages, you can use the following command:
$ sudo dpkg --purge $(dpkg -l | awk '/^rc/{print $2}')
This command will purge (remove) all packages with the "rc" status on your system. However, exercise caution when using this command and ensure that the packages you are removing are no longer needed, as they might contain important configuration files.
Now let us verify the list of installed Kernels using command:
$ <strong>dpkg --list | grep linux-image</strong> ii linux-image-5.15.0-41-generic 5.15.0-41.44 amd64 Signed kernel image generic ii linux-image-5.19.0-42-generic 5.19.0-42.43~22.04.1 amd64 Signed kernel image generic ii linux-image-generic-hwe-22.04 5.19.0.42.43~22.04.15 amd64 Generic Linux kernel image
See? This time we get only the installed Linux Kernels. The Linux Kernels marked as "rc" are gone!
We now have two installed Kernels in our Ubuntu system, the currently running Kernel and one previous version acting as backup Kernel. What if you want to keep only the current Kernel and delete everything else? You can use the following one-liner commands.
1.5. One-liner Commands to Purge Old Unused Kernels in Debian-based Systems
Command 1:
To retain only the currently running Linux Kernel and and remove all other old, unused Kernels in Debian-based systems, run this:
$ echo $(dpkg --list | grep linux-image | awk '{ print $2 }' | sort -V | sed -n '/'`uname -r`'/q;p') $(dpkg --list | grep linux-headers | awk '{ print $2 }' | sort -V | sed -n '/'"$(uname -r | sed "s/\([0-9.-]*\)-\([^0-9]\+\)/\1/")"'/q;p') | xargs sudo apt-get -y purge
Let us break down the above command and see what each option does.
- echo: This command is used to display the output of the following command substitution.
- $(dpkg --list | grep linux-image | awk '{ print $2 }' | sort -V | sed -n '/'uname -r'/q;p'): This portion of the command retrieves a list of installed Linux kernel image packages, filters out the currently running kernel version using uname -r, and selects all the older versions. The list is then printed.
- $(dpkg --list | grep linux-headers | awk '{ print $2 }' | sort -V | sed -n '/'"$(uname -r | sed "s/\([0-9.-]*\)-\([^0-9]\+\)/\1/")"'/q;p'): This section retrieves a list of installed Linux kernel header packages, filters out the currently running kernel version, and selects all the older versions. The list is then printed.
- | xargs sudo apt-get -y purge: The xargs command takes the output from the previous two commands and passes it as arguments to sudo apt-get -y purge. This removes the listed kernel packages and their associated configuration files.
In summary, the command identifies older versions of installed Linux kernel image and header packages, and then performs a purge operation to remove them using apt-get.
It helps to automatically remove old, unused kernels from the system. However, it is essential to exercise caution and verify the list of packages to be removed before executing the command to avoid removing any critical kernels.
Command 2:
Below is yet another one-liner command to keep only the currently running Linux Kernel and delete all other Kernels.
$ sudo apt-get purge $(for tag in "linux-image" "linux-headers"; do dpkg-query -W -f'${Package}\n' "$tag-[0-9]*.[0-9]*.[0-9]*" | sort -V | awk 'index($0,c){exit} //' c=$(uname -r | cut -d- -f1,2); done)
This command will remove old unused Linux kernels and their associated headers using the apt-get purge command. Let's break down what the code does:
- It starts with the $(...) construct, which allows command substitution. The output of the enclosed command will be used as arguments for apt-get purge.
- The command inside the command substitution is a loop that iterates over two tags: "linux-image" and "linux-headers". These tags are used to identify the packages related to the Linux kernel and its headers.
- Within the loop, the dpkg-query command is used to list the installed packages matching a specific pattern. The pattern is constructed using the tag and a version pattern ([0-9]*.[0-9]*.[0-9]*) to match package names like "linux-image-x.x.x" or "linux-headers-x.x.x". The -W option makes dpkg-query output the package name only.
- The output of dpkg-query is piped to sort -V, which performs a version sort. This ensures that the kernels are sorted in ascending order based on their version numbers.
- The sorted list of packages is then piped to awk for further processing. The awk command is used to find the first package that contains the current kernel version ($(uname -r | cut -d- -f1,2)). It compares each package name with the kernel version using index($0, c). When a match is found, awk exits, and the remaining packages are discarded.
- The result of the awk command is then used as input for apt-get purge. It will remove the listed packages, effectively removing the old unused Linux kernels and their headers.
In summary, this command removes all the old Linux kernel and header packages that have a version number lower than the currently running kernel. It's a more automated way of removing unused kernels without having to manually specify each version number.
2. Delete Old Unused Kernels in RHEL, Fedora, CentOS, AlmaLinux and Rocky Linux
Here are the steps to remove old unused kernels in RHEL, Fedora and RHEL-based systems such as CentOS, AlmaLinux and Rocky Linux.
1. Update your system:
Before removing old kernels, it's recommended to update your system's packages and active kernel. You can do this by running the following command:
$ sudo dnf update
This command will update all packages and the active kernel in your system.
2. Check the current kernel version:
To avoid accidentally removing the kernel you're currently using, you should check your current kernel version. You can do this with the following command:
$ uname -r
This command will display the kernel version.
If you want to display both the kernel name and version, add -s flag.
$ uname -sr
3. List all installed kernels:
To see all the kernels that are installed on your system, use the following command:
$ sudo rpm -q kernel
This command will list all the kernels installed on your system
4. Remove old kernels:
You can use the DNF command to remove old unused kernels. The following command will keep the latest two kernels (assuming the latest one is active) and remove all the others:
$ sudo dnf remove --oldinstallonly --setopt installonly_limit=2 kernel
Here's a breakdown of the command:
- sudo: This stands for "superuser do". It allows a permitted user to execute a command as the superuser or another user, as specified in the sudoers file. Essentially, it gives you administrative privileges to run the command.
- dnf: This is the package manager for RHEL, CentOS, and Fedora. It's used to install, update, and remove packages on these Linux distributions.
- remove: This is a DNF command that removes the specified packages from the system along with any packages dependent on the packages being removed.
- --oldinstallonly: This option tells DNF to target only those packages installed by the installonly command, which are typically kernels.
- --setopt installonly_limit=2: This option sets a configuration option on the fly. In this case, it sets the installonly_limit option to 2, which limits the number of versions of any single package designated as "installonly" (like kernels) that can be installed at the same time to 2.
- kernel: This is the package that the DNF command is acting on. In this case, it's the Linux kernel.
So, to summarize, this command will remove all but the 2 most recent versions of the kernel that were installed via the installonly command. It's a way to clean up old kernel versions that you're no longer using.
Be aware that this command only works if the latest kernel is active. If an older version is functional, the command will unsuccessfully try to remove it.
3. Delete Linux Kernels in Older RHEL Versions
If you're using an older version of CentOS/RHEL, you can use the package-cleanup utility from the yum-utils package to remove old kernel versions.
First, make sure yum-utils package is installed.
$ sudo yum install yum-utils
Now run the following command below to keep the latest 2 kernels and remove the rest.
$ sudo package-cleanup --oldkernels --count=2
This method has stopped working with the release of CentOS 8, but it still works for older versions of CentOS/RHEL.
Please remember to proceed with caution when performing these steps. It's always a good idea to keep at least one or two old kernels as a backup in case there's an issue with the current one. Always verify the kernel versions and ensure that your current kernel is not removed. It's also recommended to perform a system backup before making these changes.
Frequently Asked Questions
Here's a few FAQs about removing unnecessary Linux kernels.
Q: Why should I remove old kernels from my system?A: Keeping old kernels can take up disk space. Removing old kernels is essential for optimizing disk space, enhancing system performance, improving security, and simplifying maintenance. It helps prevent storage shortages, ensures up-to-date security patches, streamlines the boot process, and simplifies system management. While it's a good practice to keep a couple of older versions as backup, you can remove the rest to free up some space.
Q: How do I know which kernel I'm currently using?A: You can check your current kernel version by running the command uname -r in the terminal. This command will display the kernel name and version.
Q: How can I identify the installed Linux kernels on Debian-based systems?A: There are several ways to identify installed Linux kernels:1. Use the command dpkg --list | grep linux-image to list installed kernel packages.2. Check the /boot directory for files starting with "vmlinuz-" or "vmlinuz." followed by the kernel version.3. Run the command uname -r to display the version of the currently running kernel.
Q: How can I see all the kernels installed on RHEL-based systems?A: To list all the kernels installed on your system, you can use the command sudo rpm -q kernel. This command will list all the kernels installed on your system.
Q: Can I use sudo apt autoremove --purge to remove old kernels on Debian-based systems?A: No, sudo apt autoremove --purge typically removes automatically installed packages that are no longer needed but does not specifically target old kernels. It may not remove "rc" packages, which are removed but still have configuration files present.
Q: What is the command to remove old kernels on my RHEL or CentOS system?A: You can use the command sudo dnf remove --oldinstallonly --setopt installonly_limit=2 kernel to remove all but the 2 most recent versions of the kernel. Please note that this command only works if the latest kernel is active. If an older version is functional, the command will unsuccessfully try to remove it.
Q: I'm using an older version of CentOS/RHEL, is there a different command to remove old kernels?A: Yes, if you're using an older version of CentOS/RHEL, you can use the package-cleanup utility from the yum-utils package to remove old kernel versions. The command sudo package-cleanup --oldkernels --count=2 will keep the latest 2 kernels and remove the rest.
Q: What do the package status indicators "ii" and "rc" mean in the output of dpkg --list?A: In the output, "ii" stands for "installed, and successfully installed/configured," indicating an installed and functional package. "rc" stands for "removed, but the configuration files are still present," indicating a removed package with configuration files remaining.
Q: What precautions should I take before removing old kernels?A: It's always a good idea to keep at least one or two old kernels as a backup in case there's an issue with the current one. Always verify the kernel versions and ensure that your current kernel is not removed. It's also recommended to perform a system backup before making these changes.
Conclusion
Managing Linux kernels effectively is a crucial aspect of system administration. Over time, as systems are updated and new kernel versions are installed, it's common for old and unused kernels to accumulate. These old kernels can take up valuable disk space and, in some cases, could pose a security risk if they contain vulnerabilities. So it is recommended to clean up older and unused Kernels once in a while.
However, it's essential to approach the task of removing old kernels with caution. While freeing up disk space is beneficial, each kernel serves as a fallback if the current version fails or encounters issues. Therefore, it's recommended to always keep at least one or two old kernels as a safety measure.
As always, prior to making significant changes to your system, ensure you have a current backup and understand the implications of the commands you're executing. If done correctly, the process of removing old kernels can contribute to a more efficient and secure Linux environment.
Reference:
- Askubuntu Forum
以上是如何刪除舊未使用的Linux內核的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Linux管理員的平均年薪在美國為75,000至95,000美元,歐洲為40,000至60,000歐元。提升薪資可以通過:1.持續學習新技術,如雲計算和容器技術;2.積累項目經驗並建立Portfolio;3.建立職業網絡,拓展人脈。

Linux系統管理員的主要任務包括系統監控與性能調優、用戶管理、軟件包管理、安全管理與備份、故障排查與解決、性能優化與最佳實踐。 1.使用top、htop等工具監控系統性能,並進行調優。 2.通過useradd等命令管理用戶賬戶和權限。 3.利用apt、yum管理軟件包,確保系統更新和安全。 4.配置防火牆、監控日誌、進行數據備份以確保系統安全。 5.通過日誌分析和工具使用進行故障排查和解決。 6.優化內核參數和應用配置,遵循最佳實踐提升系統性能和穩定性。

Linux和Windows在虛擬化支持上的主要區別在於:1)Linux提供KVM和Xen,性能和靈活性突出,適合高定制環境;2)Windows通過Hyper-V支持虛擬化,界面友好,與Microsoft生態系統緊密集成,適合依賴Microsoft軟件的企業。

Linux的主要用途包括:1.服務器操作系統,2.嵌入式系統,3.桌面操作系統,4.開發和測試環境。 Linux在這些領域表現出色,提供了穩定性、安全性和高效的開發工具。

學習Linux並不難。 1.Linux是一個開源操作系統,基於Unix,廣泛應用於服務器、嵌入式系統和個人電腦。 2.理解文件系統和權限管理是關鍵,文件系統是層次化的,權限包括讀、寫和執行。 3.包管理系統如apt和dnf使得軟件管理方便。 4.進程管理通過ps和top命令實現。 5.從基本命令如mkdir、cd、touch和nano開始學習,再嘗試高級用法如shell腳本和文本處理。 6.常見錯誤如權限問題可以通過sudo和chmod解決。 7.性能優化建議包括使用htop監控資源、清理不必要文件和使用sy

多年來,Linux軟件分佈依賴於DEB和RPM等本地格式,並深深地根深蒂固。 但是,Flatpak和Snap已經出現,有望成為應用程序包裝的通用方法。 本文考試

本指南探討了用於比較Linux中文本文件的各種方法,Linux是系統管理員和開發人員的關鍵任務。 我們將介紹命令行工具和視覺差異工具,突出顯示其優勢和適當的用例。 假設

Linux和Windows在用戶賬戶管理上的主要區別在於權限模型和管理工具。 Linux使用基於Unix的權限模型和命令行工具(如useradd、usermod、userdel),而Windows採用自己的安全模型和圖形用戶界面(GUI)管理工具。
