AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / ubuntu / Perguntas / 2793
Accepted
Hans
Hans
Asked: 2010-08-21 19:37:01 +0800 CST2010-08-21 19:37:01 +0800 CST 2010-08-21 19:37:01 +0800 CST

Como removo versões antigas do kernel para limpar o menu de inicialização?

  • 772

Toda vez que instalo um novo kernel Linux, ele fica no grub_config, tornando o menu de inicialização cada vez mais longo.

Eu sei que posso pesquisar manualmente os pacotes instalados e removê-los.

O Ubuntu fornece alguma maneira mais fácil de limpá-los ou impedi-los de aparecer na lista de inicialização?

grub2 kernel cleanup
  • 30 30 respostas
  • 1193238 Views

30 respostas

  • Voted
  1. Best Answer
    fossfreedom
    2012-02-03T16:06:07+08:002012-02-03T16:06:07+08:00

    16.04 e versões mais recentes do Ubuntu

    sudo apt autoremove
    

    Este comando remove pacotes que foram instalados automaticamente para resolver uma dependência, mas agora não são mais dependentes. Isso inclui versões antigas de linux-headers-*e linux-image-*. (Também é inteligente sobre esse processo, deixando uma versão sobressalente do kernel como substituto!)

    11.10 e versões mais recentes do Ubuntu

    GRUB2 e sua exibição de todos os kernels

    As versões mais recentes do Grub2 instaladas no Ubuntu exibem automaticamente o kernel mais recente e ocultam os kernels mais antigos que você pode ter instalado.

    GNU GRUB

    Se você não vir seu grub - lembre-se de pressionar Shiftdurante a inicialização.

    Como você pode ver, apenas o kernel mais recente é exibido.

    Se você selecionar a opção mostrada (pressione Enter), todos os kernels antigos ficarão visíveis e disponíveis para inicialização.

    GNU GRUB Versões anteriores

    Como excluir permanentemente kernels mais antigos

    Primeiro inicialize com o kernel mais recente disponível.

    Existem várias maneiras de excluir kernels antigos. Pessoalmente, eu não tocaria no Computer Janitor, pois isso é reconhecido por quebrar seu computador com suas sugestões.

    sináptica

    An alternative is Synaptic (sudo apt install synaptic)

    search for linux-image, right-click a kernel and choose complete removal and finally click the Apply button to delete the kernel.

    Gerenciador de Pacotes Synaptic

    Repeat the search but this time for linux-header - you can delete the associated headers for the kernel image chosen previously.

    Synaptic though will not attempt to verify what you are trying to remove... you could inadvertently delete your newest kernel - or even delete all of your kernels via this tool leaving you with an unbootable Ubuntu!.

    Remember to check which kernel you are using type:

    uname -r
    

    The result would be similar to:

    Terminal <uname -r>

    Remember the result and the number - make sure you don't delete the corresponding image or header.

    Recommendation

    My recommendation is to keep at least two or preferably three kernels including the latest. The reason for the recommendation is that you will have at least one/two other kernels to boot with, if for what-ever reason the latest kernel you are unable to boot with or introducing a regressed capability such as broken wireless.

    • 639
  2. penreturns
    2012-06-20T10:37:04+08:002012-06-20T10:37:04+08:00

    First, reboot your System to be sure it is using the latest kernel. Then open terminal and check your current kernel:

    uname -r 
    

    DO NOT REMOVE THIS KERNEL!

    Next, type the command below to view/list all installed kernels on your system.

    dpkg --list 'linux-image-*'
    

    Find all the kernels that lower than your current kernel. When you know which kernel to remove, continue below to remove it. Run the commands below to remove the kernel you selected.

    sudo apt-get purge linux-image-x.x.x-x-generic 
    

    Finally, run the commands below to update grub2

    sudo update-grub2 
    

    Reboot your system.

    • 416
  3. David Kemp
    2013-02-14T02:44:16+08:002013-02-14T02:44:16+08:00

    My one-liner to remove old kernels (this also frees up disk space)

    dpkg --list | grep linux-image | awk '{ print $2 }' | sort -V | sed -n '/'`uname -r`'/q;p' | xargs sudo apt-get -y purge
    

    Explanation (remember, | uses the output of the previous command as the input to the next)

    • dpkg --list lists all installed packages
    • grep linux-image looks for the installed linux images
    • awk '{ print $2 }' just outputs the 2nd column (which is the package name)
    • sort -V puts the items in order by version number
    • sed -n '/'`uname -r`'/q;p' prints the lines before the current kernel
    • xargs sudo apt-get -y purge purges the found kernels

    Unwinding the sed invocation:

    • -n tells sed to be quiet
    • `uname -r` outputs the current installed kernel release - we include it in backticks so that the output is includes as part of the command (you might also see this as $(uname -r)
    • /something/q says stop when you match 'something' (in this case, something is output of uname -r) - the / surround a regular expression
    • p is print
    • the ; is the command separtor, so /something/q;p says quit when you match something, else print

    altogether, sed -n '/'`uname -r`'/q;p' is print the lines until it matches with the current kernel name.

    If you're paranoid (like me), you can make the last part xargs echo sudo apt-get -y purge so that the command to purge the old kernels is printed, then you can check that nothing unexpected is included before you run it.


    Modified version to remove headers:

    dpkg --list | grep 'linux-image' | awk '{ print $2 }' | sort -V | sed -n '/'"$(uname -r | sed "s/\([0-9.-]*\)-\([^0-9]\+\)/\1/")"'/q;p' | xargs sudo apt-get -y purge
    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
    

    Note: the sed invocation is modified. "$(uname -r | sed "s/\([0-9.-]*\)-\([^0-9]\+\)/\1/")" extracts only the version (e.g. "3.2.0-44") , without "-generic" or similar from uname -r


    All-in-one version to remove images and headers (combines the two versions above):

    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
    
    • 307
  4. bmaupin
    2015-05-15T07:20:21+08:002015-05-15T07:20:21+08:00

    Ubuntu 16.04+:

    $ sudo apt autoremove
    ...
    The following packages will be REMOVED:
      linux-headers-4.4.0-57 linux-headers-4.4.0-57-generic linux-image-4.4.0-57-generic linux-image-extra-4.4.0-57-generic linux-tools-4.4.0-57 linux-tools-4.4.0-57-generic
    

    Ubuntu 15.10 and below:

    I find this to be the easiest and quickest way. It keeps the latest kernel as well as two more:

    sudo apt-get install bikeshed
    sudo purge-old-kernels
    

    To change the number of additional kernels that are kept:

    sudo purge-old-kernels --keep 3
    
    • 63
  5. karthick87
    2010-11-29T22:09:39+08:002010-11-29T22:09:39+08:00

    Removendo entradas do Grub 2 As entradas devem ser removidas editando ou removendo arquivos na pasta /etc/grub.d. O arquivo /boot/grub/grub.cfg é somente leitura e normalmente não deve exigir edição.

    Muitos Kernels?

    • Se você não tem certeza do kernel que está usando atualmente, em um terminal digite uname -r .

    • Kernels removidos via APT (Synaptic, "apt-get remove", etc.) atualizarão automaticamente o grub.cfg e nenhuma ação do usuário é necessária.

    • Uma ótima ferramenta para remover kernels (e entradas de menu) é o Ubuntu-Tweak, um aplicativo GUI seguro e fácil de usar.

    • Instale o ajuste do Ubuntu

    • O Ubuntu-Tweak estará disponível em Aplicativos > Ferramentas do Sistema.

    Remover entradas mais antigas do kernel

    • Selecione “Package Cleaner” à esquerda e “Clean Kernel” no painel direito.

    • Pressione o botão "Desbloquear" no canto inferior direito, digite sua senha.

    • Selecione na lista exibida as imagens e cabeçalhos do kernel que você deseja remover. O kernel em uso não está listado.

    • Pressione o botão "Limpar" no canto inferior direito para remover as imagens e cabeçalhos do kernel selecionados.

    Remover sistemas operacionais do menu Grub

    • Outros sistemas operacionais que foram removidos do computador também serão removidos do menu assim que "update-grub" for executado como root.

    • Os itens de menu são colocados no menu Grub2 por scripts. Se você não quiser que outros sistemas operacionais sejam inseridos no menu, desative /etc/grub.d/30_osprober

    • Execute este comando para interromper a execução do script
      sudo chmod -x /etc/grub.d/30_os-prober

    • DISABLE_30_OS-PROBER='true' em /etc/default/grub

    Remova o Memtest86+ do menu Grub
    sudo chmod -x /etc/grub.d/20_memtest86+

    • Execute o comando update-grub para permitir que as alterações sejam incorporadas no grub.cfg

    Fonte

    Nota: Após as atualizações do kernel, uma nova entrada é adicionada ao menu GRUB. Você pode remover a mais antiga, se desejar. precisa inicializar uma versão mais antiga do kernel para fins de solução de problemas.

    Maneira alternativa de remover entradas do Kernel (antes de 10.04)

    para GRUB não GRUB2

    gerente de startup Instalar gerenciador de inicialização

    Você pode encontrá-lo em System>>Administration>> texto alternativo
    texto alternativo
    Você vê na segunda captura de tela que pode selecionar quantos kernels mostrar? Eu geralmente apenas o mantenho em 1, mas quando recebo uma atualização do kernel, sempre o mudo para 2 antes de reiniciar, para que eu possa selecionar o kernel mais antigo se o novo kernel tiver problemas com meu hardware. Uma vez que eu sei que o novo kernel está funcionando bem, eu o mudo de volta para 1.

    • 44
  6. Kees Cook
    2010-09-18T08:35:05+08:002010-09-18T08:35:05+08:00

    Puramente linha de comando, isso removerá todos, exceto o atual e o segundo mais atual (através do "-2" no comando head abaixo):

    OLD=$(ls -tr /boot/vmlinuz-* | head -n -2 | cut -d- -f2- |
        awk '{print "linux-image-" $0 " linux-headers-" $0}' )
    if [ -n "$OLD" ]; then
        apt-get -qy remove --purge $OLD
    fi
    apt-get -qy autoremove --purge
    
    • 41
  7. jarno
    2015-01-09T06:36:33+08:002015-01-09T06:36:33+08:00

    Update: purge-old-kernels is deprecated nowadays.

    I made a script to purge kernels even in tricky conditions. It is called linux-purge and you can find it here.

    If you just want to purge the kernels (and the related packages) that are older than the currently used kernel, when system is not broken, you could use this script.

    There is also an Ubuntu documentation page that I have contributed to concerning removing old kernels here.

    • 39
  8. Qwerty
    2012-02-16T01:30:51+08:002012-02-16T01:30:51+08:00

    You can follow the Using the "unattended-upgrades" package section of Automatic Security Updates article on Ubuntu Wiki to perform this.

    You need to change the following line in /etc/apt/apt.conf.d/50unattended-upgrades file;

    //Unattended-Upgrade::Remove-Unused-Dependencies "false";
    

    with

    Unattended-Upgrade::Remove-Unused-Dependencies "true";
    

    to automatically remove old packages, including kernels.

    Also remove or comment the line

    "^linux-image.*"; 
    

    in the "NeverAutoRemove" section of the file /etc/apt/apt.conf.d/01autoremove.

    • 30
  9. Luis Alvarado
    2013-04-08T17:13:29+08:002013-04-08T17:13:29+08:00

    The fastest/simpler way (Applicable at least since 12.04) possible that already comes with Ubuntu is apt-get. Do the following if you wish to remove all older kernel versions that are not in use (Except the previous one that you are no using. This is to make sure that if the current kernel version fails in some way, you have a way to go back to a previous state). Do the following:

    sudo apt-get autoclean
    

    This will eliminate any old files (Including kernel versions) you may have. Note that if you have many old versions, it will take a while since it has to make sure that removing the kernel version has no issues. For me, removing the last 12 kernel versions took about 2 minutes. You can also do the following:

    sudo apt-get clean
    

    Which will eliminate everything downloaded and stored in the cache folder of apt. Lastly you have:

    sudo apt-get autoremove
    

    which would check for any unused packages and remove them if necessary. This is great for those libraries and dependency packages that are no longer needed byt any app installed.

    • 28
  10. mikewhatever
    2011-10-11T06:25:36+08:002011-10-11T06:25:36+08:00

    Para descobrir quais kernels e cabeçalhos estão instalados, use

    dpkg -l | grep linux-image
    
    dpkg -l | grep linux-headers
    

    Você pode removê-los um por um ou juntos, apenas certifique-se de manter o mais recente.

    Existem também alguns comandos e scripts úteis para automatizar a remoção.

    http://ubuntuforums.org/showthread.php?t=1658648

    As seguintes reivindicações para remover todos os kernels e cabeçalhos não utilizados:

    dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]\+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d'|grep -E "(image|headers|modules)" | grep -v hwe | xargs sudo apt-get purge
    

    (use apt-get -ypara remover sem questionar)

    Aqui está o que acontece quando executado em 18.04.1:

    ~$ dpkg -l 'linux-*' | sed '/^ii/!d;/'"$(uname -r | sed "s/\(.*\)-\([^0-9]
    
    \+\)/\1/")"'/d;s/^[^ ]* [^ ]* \([^ ]*\).*/\1/;/[0-9]/!d'|grep -E "(image|headers|modules)" | xargs sudo apt-get -y purge
    Reading package lists... Done
    Building dependency tree       
    Reading state information... Done
    The following packages will be REMOVED:
      linux-headers-4.15.0-33* linux-headers-4.15.0-33-generic* linux-headers-4.15.0-34* linux-headers-4.15.0-34-generic* linux-image-4.15.0-33-generic* linux-image-4.15.0-34-generic*
      linux-modules-4.15.0-33-generic* linux-modules-4.15.0-34-generic* linux-modules-extra-4.15.0-33-generic* linux-modules-extra-4.15.0-34-generic*
    0 upgraded, 0 newly installed, 10 to remove and 1 not upgraded.
    After this operation, 671 MB disk space will be freed.
    (Reading database ... 227403 files and directories currently installed.)
    Removing linux-headers-4.15.0-33-generic (4.15.0-33.36) ...
    Removing linux-headers-4.15.0-33 (4.15.0-33.36) ...
    Removing linux-headers-4.15.0-34-generic (4.15.0-34.37) ...
    Removing linux-headers-4.15.0-34 (4.15.0-34.37) ...
    Removing linux-modules-extra-4.15.0-33-generic (4.15.0-33.36) ...
    Removing linux-image-4.15.0-33-generic (4.15.0-33.36) ...
    /etc/kernel/postrm.d/initramfs-tools:
    update-initramfs: Deleting /boot/initrd.img-4.15.0-33-generic
    /etc/kernel/postrm.d/zz-update-grub:
    Generating grub configuration file ...
    Found linux image: /boot/vmlinuz-4.15.0-36-generic
    Found initrd image: /boot/initrd.img-4.15.0-36-generic
    Found linux image: /boot/vmlinuz-4.15.0-34-generic
    Found initrd image: /boot/initrd.img-4.15.0-34-generic
    Adding boot menu entry for EFI firmware configuration
    done
    Removing linux-modules-extra-4.15.0-34-generic (4.15.0-34.37) ...
    Removing linux-image-4.15.0-34-generic (4.15.0-34.37) ...
    I: /vmlinuz.old is now a symlink to boot/vmlinuz-4.15.0-36-generic
    I: /initrd.img.old is now a symlink to boot/initrd.img-4.15.0-36-generic
    /etc/kernel/postrm.d/initramfs-tools:
    update-initramfs: Deleting /boot/initrd.img-4.15.0-34-generic
    /etc/kernel/postrm.d/zz-update-grub:
    Generating grub configuration file ...
    Found linux image: /boot/vmlinuz-4.15.0-36-generic
    Found initrd image: /boot/initrd.img-4.15.0-36-generic
    Adding boot menu entry for EFI firmware configuration
    done
    Removing linux-modules-4.15.0-33-generic (4.15.0-33.36) ...
    Removing linux-modules-4.15.0-34-generic (4.15.0-34.37) ...
    (Reading database ... 156180 files and directories currently installed.)
    Purging configuration files for linux-image-4.15.0-34-generic (4.15.0-34.37) ...
    Purging configuration files for linux-modules-4.15.0-33-generic (4.15.0-33.36) ...
    dpkg: warning: while removing linux-modules-4.15.0-33-generic, directory '/lib/modules/4.15.0-33-generic' not empty so not removed
    Purging configuration files for linux-modules-4.15.0-34-generic (4.15.0-34.37) ...
    Purging configuration files for linux-image-4.15.0-33-generic (4.15.0-33.36) ...
    Purging configuration files for linux-modules-extra-4.15.0-34-generic (4.15.0-34.37) ...
    Purging configuration files for linux-modules-extra-4.15.0-33-generic (4.15.0-33.36) ...
    ~$ uname -r
    4.15.0-36-generic
    
    • 27

relate perguntas

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Como adicionar um diretório ao PATH?

    • 17 respostas
  • Marko Smith

    Como listar todos os pacotes instalados

    • 24 respostas
  • Marko Smith

    Como faço para obter a temperatura da CPU?

    • 21 respostas
  • Marko Smith

    Como posso adicionar um usuário como um novo sudoer usando a linha de comando?

    • 7 respostas
  • Marko Smith

    Alterar permissões e propriedade da pasta

    • 9 respostas
  • Marko Smith

    Como você reinicia o Apache?

    • 13 respostas
  • Marko Smith

    Como posso desinstalar o software?

    • 11 respostas
  • Marko Smith

    Como os PPAs podem ser removidos?

    • 26 respostas
  • Martin Hope
    justingrif Como adicionar um diretório ao PATH? 2009-07-23 12:42:23 +0800 CST
  • Martin Hope
    NES Como habilitar ou desabilitar serviços? 2010-12-30 13:03:32 +0800 CST
  • Martin Hope
    Ivan Como listar todos os pacotes instalados 2010-12-17 18:08:49 +0800 CST
  • Martin Hope
    Olivier Lalonde Como manter os processos em execução após encerrar a sessão ssh? 2010-10-22 04:09:13 +0800 CST
  • Martin Hope
    David B Como posso adicionar um usuário como um novo sudoer usando a linha de comando? 2010-10-16 04:02:45 +0800 CST
  • Martin Hope
    Hans Como removo versões antigas do kernel para limpar o menu de inicialização? 2010-08-21 19:37:01 +0800 CST
  • Martin Hope
    David Barry Como determino o tamanho total de um diretório (pasta) na linha de comando? 2010-08-06 10:20:23 +0800 CST
  • Martin Hope
    jfoucher "Os seguintes pacotes foram retidos:" Por que e como resolvo isso? 2010-08-01 13:59:22 +0800 CST
  • Martin Hope
    David Ashford Como os PPAs podem ser removidos? 2010-07-30 01:09:42 +0800 CST

Hot tag

10.10 10.04 gnome networking server command-line package-management software-recommendation sound xorg

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve