Note to vistors: while it is possible, it is highly inadvisable to remove the running kernel. If that kernel is the only one installed, and you reboot or lose power after uninstalling or deleting it, your system will be unbootable and you will probably have to reinstall. Recovery mode will not work. If this happens, you can boot from a live system to rescue your data and possibly copy kernel files to the right locations. There is normally no reason to uninstall the running kernel. So you probably should not follow this answer :)
You stated in comments that you want to avoid the dialog that appears when you use package management tools to remove the running kernel. The only way I can think of to achieve this is to delete all the files belonging to the running kernel.
We are going to use
locate to find the kernel's files. First update its database.
If for some reason you don't want to delete the
dpkg database records for the kernel, run this command instead of the above:
sudo updatedb --prunepaths=/var/lib/dpkg
Find the running kernel and its modules, etc:
locate -be $(uname -r)
Check the list. To remove ALL the files that belong to the kernel, even the many small files in
/usr/src, omit the
-b flag from
locate. When you have the list you want, pipe the results to
xargs to delete the files:
locate -be $(uname -r) -0 | xargs -0 sudo rm -r
xargs interactive, you can add the
-p flag and it will prompt you to confirm that you really do want to run
rm on each file in the list. If you omit
locate and add
xargs, you will be confirming for a long time.
It is not really necessary to use
-0 flags to get null-delimited output because all these files will have sane names unless you or someone else has tinkered with them. But it is good practice to use null-delimiting with
xargs, because it makes mistakes if any filename has a space.
To prevent GRUB attempting to boot or giving you the option of booting a non-existent kernel, update the configuration:
I just tested this, and right now, I am typing this from the system on which I've deleted the running kernel in this way (I booted from an older Ubuntu kernel to do this, because I normally use a patched kernel that
dpkg doesn't know about, and I don't want to delete it and compile it again).
The kernel is in RAM. It is loaded into RAM at boot time, so it doesn't need its files right now. However, I'm now going to reinstall the kernel using these commands:
sudo apt update
sudo apt install --reinstall linux-image-$(uname -r) \
linux-modules-extra-$(uname -r) \
linux-headers-$(uname -r) \
Since you seem to be interested in a non-interactive process, I'll mention that you can use
apt-get in preference to
apt if you wish to capture any output into a file for later use.