Ошибка при загрузке grub

Нередко возникает необходимость в установке двух принципиально разных операционных систем на один компьютер: Windows и Linux. Разумеется, подобное «соседство» будет связано с некоторыми неудобствами. Для установки, как правило, используют специальную программу GRUB. Но к сожалению, при её использовании можно столкнуться с рядом ошибок. В этой статье разберёмся с тем, как исправить ошибки загрузчика GRUB. Давайте же начнём. Поехали!

Исправление ошибок GRUB

Для начала давайте определимся с тем, что из себя представляет эта программа. GRUB — представляет собой системный загрузчик, устанавливающийся непосредственно с Линукса и записывающий все данные на первый раздел диска (MBR).

Сам rescue mode является отличительной чертой GRUB 2 от его предыдущей версии. Этот режим запускается, если программе-загрузчику не удалось найти файл «grub.cfg» либо не удалось передать управление в kernel (ядро). В итоге не удаётся найти загрузочные файлы и запустить операционную систему. Именно тогда и возникает ошибка.

Ошибка: Unknown Filesystem

Следуйте инструкциям ниже, чтобы узнать, как решить проблему с GRUB

Способ 1

Что делать в случае ошибки unknown filesystem grub-rescue? Перед вами окно, в котором можно использовать только 4 команды, их вполне достаточно, чтобы исправить все проблемы и успешно загрузиться:

  • ls — позволяет вывести всё содержимое;
  • set — применяется для установки переменных;
  • unset — очищает переменную;
  • insmod — необходима для загрузки модулей.

Также можно сделать доступным ряд других команд. Сделать их доступными можно, загрузив модуль «normal». Для этого пропишите:

insmod normal

После этого станут доступны:

  • dump — для очистки памяти;
  • exit — команда выхода из загрузчика;
  • chainloader — необходима, чтобы указать последующей команде boot передать управление цепочечному загрузчику;
  • kfreebsd — несколько команд, позволяющих загрузить ядро FreeBSD, его модули;
  • rmmod — позволяет выгрузить указанный модуль ядра;
  • multiboot.

Первым делом нужно отыскать модули, чтобы загрузить их. Для этого введите:

ls

Результатом выполнения команды будет следующее:

(hd0) (hd0,msdos3) (hd0,msdos2) (hd0,msdos1) (hd1) (hd1,msdos2) (hd1,msdos1)

Из этого можно сделать вывод, что загрузчик не может определить файловые системы дисков, поэтому определяет их как msdos. Теперь необходимо угадать видимые диски. В конкретном примере перед вами два диска: hd0 (с тремя разделами) и hd1 (с двумя разделами). Допустим, вы знаете, что Linux инсталлирован на диск, который имеет три раздела. В таком случае вам нужен диск с индексом «0».

GRUB даёт названия разделам в обратном порядке. В связи с этим, неясно как трактовать запись: «(hd0,msdos3)». Ведь можно посчитать это как первым разделом, так и третьим. К счастью, из этой ситуации можно выйти при помощи такого синтаксиса команды: «(hd0,1)». Обратите внимание, что в программе-загрузчике GRUB отсчёт дисков идёт с 0, а разделов с 1.

Допустим, что Линукс хранится в первом разделе, тогда он будет обозначаться (hd0,1). В этом случае команда, которую необходимо прописать, будет иметь вид:

set prefix=(hd0,1)/boot/grub
set root=(hd0,1)

Теперь модули могут быть загружены. Использовать их можно только после загрузки.

После того как вы выбрали нужный диск, проверьте содержится ли там то, что нужно. Для этого пропишите:

ls /boot/grub

В результате выполнения на экране появится список md файлов.

Далее, пропишите:

insmod ext2
insmod normal
normal

После этого загрузчик будет переведён в режим полной функциональности. Затем автоматически будут найдены разделы с операционной системой, и откроется меню программы.

Теперь остаётся загрузить Linux. Делается это при помощи команды:

grub-install /dev/sda

Ноутбук с ОС Linux

Способ 2

Всё сильно упрощается, если использовать Live CD – загрузочный диск с системой Linux. Он может быть записан на флешке, на внешнем винчестере или на обычном диске – это неважно, главное, чтобы с него можно было загрузить компьютер.

После загрузки Linux стандартным способом устанавливается бесплатная утилита Boot Repair. Она предназначена именно для устранения ошибок загрузки с помощью загрузчика Grub и очень проста в использовании – достаточно кликнуть по кнопке.

Заметим, что иметь Live CD для линуксоида всегда полезно и даже необходимо. Это зачастую избавляет от множества проблем, так как позволяет загрузить полноценную систему с внешнего носителя и использовать весь её инструментарий. Скачать такой диск с любой версией Linux не представляет сложностей, в комплекте обычно идёт инструкция по записи его на флешку.

После выполнения всех этих действий ошибка будет устранена. Пишите в комментариях была ли полезна для вас эта статья и задавайте любые интересующие вопросы по рассмотренной теме.

Contents

  1. Overview
  2. GRUB 2 Terminal Commands

    1. Normal
    2. grub>
    3. grub rescue>
  3. General Troubleshooting Preparation

    1. Boot-Repair
    2. Search & Set

      1. How & Where to Search
  4. Specific Troubleshooting

    1. grub>
    2. grub rescue>
    3. GRUB
  5. Editing the GRUB 2 Menu During Boot

    1. Key Points About Terminal Menu Editing:
    2. Menu Editing Examples
  6. Post Boot Follow Up
  7. Fallback mode
  8. GRUB 2 Errors

    1. Selected Problems and Bugs

      1. External Drive Installs and »grub-pc» Updates
      2. External Drive Installs and MBR Selection
      3. Boot Partition is in Logical Volume whose Volume Group contains a snapshot
      4. insmod fails with «error: no such disk»
  9. Links

This page provides the user with information on options available for repairing GRUB 2 boot issues and specific instructions on how to use the GRUB 2 terminal. The instructions are written for GRUB 1.99, which is the version of GRUB 2 which is included on Ubuntu 11.04, Natty Narwhal, and later. Differences for version 1.98 (Ubuntu 10.4, Lucid Lynx) are noted when the procedures differ.

  • g2_grub_rescue1.png

GRUB 2’s ability to fix boot problems is greatly improved over the original GRUB bootloader. In addition to an automatic fallback mode if booting from a menuentry in a submenu, GRUB 2 allows the user to edit its menu before the operating system is loaded. The rescue mode GRUB 2 terminal can help boot an operating system so that permanent repairs to system files can be made.

The instructions on this page are written for a fully-installed Ubuntu operating system. WUBI boot problems are not covered in detail although they are addressed in several sections.

Overview

GRUB 2 boot problems can leave the system in several states. The user may see one of the following displays on the monitor when a boot fails. The display provides the first indication of what might be causing the failure to boot. Here are the failure prompts and displays, and the possible cause of each:

  • grub> prompt: GRUB 2 loaded modules but was unable to find the grub.cfg file.

  • grub rescue> prompt: GRUB 2 failed to find its grub folder, or failed to load the normal module.

  • grub>: — The grub prompt on a blank screen.

    • GRUB 2 has found the boot information but has been either unable to locate or unable to use an existing GRUB 2 configuration file (usually grub.cfg).

  • grub rescue>: — The rescue mode.

    • GRUB 2 is unable to find the grub folder or its contents are missing/corrupted. The grub folder contains the GRUB 2 menu, modules and stored environmental data.

  • GRUB — a single word at the top left of the screen, with no prompt and no cursor.

    • GRUB has failed to find even the most basic information, usually contained in the MBR or boot sector.
  • Busybox or Initramfs: GRUB 2 began the boot process but there was a problem passing control to the operating system. Possible causes include an incorrect UUID or root= designation in the ‘linux’ line or a corrupted kernel.

  • Frozen splash screen, blinking cursor with no grub> or grub rescue prompt. Possible video issues with the kernel. While these failures are not of GRUB 2’s making, it may still be able to help. GRUB 2 allows pre-boot editing of its menu and the user may restore functionality by adding and/or removing kernel options in a menuentry before booting.

Each of the GRUB 2 failure modes can normally be corrected either from the GRUB 2 terminal or by using an Ubuntu LiveCD. Additionally, there are compatible 3rd party bootable «rescue» CD/USB options which may also work. If using an Ubuntu LiveCD, it is recommended, but not always necessary, to use the same version CD as the system you are trying to repair. This ensures compatability of any modules and configuration files that may be loaded while attempting to repair the system.

GRUB 2 Terminal Commands

info.png Here are some useful tips and features for use with the GRUB 2 terminal:

  • Turning off the splash image. This may make viewing the terminal easier. Press c at the GRUB 2 menu to get to the command line and then type: set color_normal=white/blue or the color combination you wish to use. «black» as the second entry retains the menu’s transparency and should be avoided as a selection if the user wants to work with a solid background color.

  • TAB completion. This feature is very handy. At any point, pressing the TAB key may complete an entry, if the element is unique, or display available options. Typing a few additional characters and pressing TAB again may allow tab completion to finish the entry.

  • set pager=1 To prevent text from scrolling off the screen, type set pager=1.

  • Help. Type help to view a list of all the commands. Type help x to view help commands beginning with the letter «x». Tab completion and using the up arrow to repeat commands work the same as in a normal terminal.

Normal

When GRUB 2 is fully functional, the GRUB 2 terminal is accessed by pressing c. If the menu is not displayed during boot, hold down the SHIFT key until it appears. If it still does not appear, try pressing the ESC key repeatedly.

From a GRUB 2 terminal with the grub> prompt, a wide variety of commands are available.

  • A few of the more important commands:

    Command

    Result / Example

    boot

    Initiate the boot sequence, also F10 or CTRL-x

    cat

    Display the contents of readable files; cat (hd0,1)/boot/grub/grub.cfg

    configfile

    Load a GRUB 2 configuration file such as grub.cfg; configfile (hd0,5)/boot/grub/grub.cfg

    initrd

    Loads the initrd.img, necessary for booting; initrd (hd0,5)/initrd.img

    insmod

    Loads a module; insmod (hd0,5)/boot/grub/normal.mod, or insmod normal

    linux

    Loads the kernel; insmod /vmlinuz root=(hd0,5) ro

    loop

    Mount a file as a device; loopback loop (hd0,2)/iso/my.iso

    ls

    Lists the contents of a partition/folder; ls, ls /boot/grub, ls (hd0,5)/, ls (hd0,5)/boot

    lsmod

    List loaded modules

    normal

    Activate the normal module, if loaded

    search

    Search for a device. Type help search for the available options.

    set

    Review current settings, or set XXX to set a variable such as colors, prefix, root

    vbeinfo

    Display GRUB 2 available resolutions

    To view the complete command list, type help. For details on a particular command, type help [command]

grub>

When GRUB 2 is unable to boot or display the GRUB 2 menu the system will be left at a GRUB 2 terminal if possible. If the system boots to the grub> prompt, the usual modules and commands are normally available. The user may need to manually load modules using the insmod [module] command before some commands will work.

grub rescue>

In the grub rescue mode, only a limited set of commands are available. These commands are sufficient to investigate the contents of the drives, set prefix (path to the grub folder) and root (partition), load modules and boot.

The rescue mode provides fewer commands than the normal GRUB prompt line, but also provides these additional commands:

  • Command

    Result / Example

    dump

    Clears memory

    exit

    Exit GRUB 2

    normal

    Return to the standard «grub>» mode if possible.

Among the commands which can be used in the grub rescue mode:

  • boot

    cat

    chain

    help

    insmod

    linux

    ls

    multiboot

    normal

    search

    set

    unset

General Troubleshooting Preparation

Boot-Repair

The majority of this guide is devoted to working with the GRUB 2 terminal, which is used to enter commands to attempt to repair a broken bootloader. info.png Boot-Repair is a GUI application which can automatically analyze boot problems and select the proper course of action to repair them. Its simple interface provides beginners as well as experienced Linux users an easy method of repairing the majority of GRUB 2 problems.

Additionally, Boot-Repair contains an automated method to run a boot info script which performs a series of tests and provides a file containing much valuable information regarding the status of the computer’s operating and boot systems. This file can be inspected by community helpers on forums or IRC channels to help diagnose boot problems.

Boot-Repair can be run from a LiveCD or an operating Linux system. To download the package run the following commands:

  • sudo add-apt-repository ppa:yannubuntu/boot-repair && sudo apt-get update
    sudo apt-get install -y boot-repair && boot-repair

Visit the Boot-Repair community document for more information.

Boot-Repair is available from the Launchpad repositories and can be run from a CD or a working Linux OS.

Search & Set

A great many boot problems are due to incorrect paths to required files. The GRUB 2 terminal, in either ‘failure’ mode, provides a robust ability to search hard drive(s) and partitions and to inspect their contents.

In order to boot successfully, the root, prefix, linux and initrd variables must be correct. The user must verify the paths and names of these items. If they are incorrect, use the commands below to find and fix them. GRUB 2 variable settings can be viewed with the set command.

In the following examples, X is a hard drive number; Y is a partition number. If a command example includes either of these replace them with the appropriate value.

How & Where to Search

In the graphic below, the text in red are commands to be entered by the user, and text in green is the output of the command on an operating system (i.e. what you would like to see if your Ubuntu installation is on sda1).

g2_grub_set_color.png

  • The first hard drive is 0. The first partition is 1. Thus sda1 becomes (hd0,1), sdb5 is (hd1,5).

  • Use the ls command in the follow manner

  • «Tab completion» may work — enter part of the filename and press the TAB key.

Command

Purpose

ls

Search the entire computer for devices and partitions: (hd0) (hd1) (hd0,1) (hd0,5) (hd1,1)

ls /

Search the root directory of the device designated as root (use the set command to check root).

ls (hdX,Y)

View information about a partition — format, size, UUID, etc.

ls (hdX,Y)/

View the root contents of a partition. Use this command to look for the presence of vmlinuz and initrd.img symlinks

ls (hdX,Y)/boot/

View the contents of a folder

ls (hdX,Y)/boot/

Inspect the /boot folder. It should contain the actual kernel (linux-3.2…) and initrd image (initrd.img-3.2….)

ls (hdX,Y)/boot/grub/

Inspect the /boot/grub folder. It should contain grub.cfg and many *.mod files. If looking for a specific file, include the name in the search to limit the number of returns. If available, the command set pager=1 will also limit returns to a single screen.

What to Look For

Where It Should Be (Default Installation)

Specific / General Search Example

grub.cfg

(hdX,Y)/boot/grub/ or /boot/grub/

ls (hdX,Y)/boot/grub/grub.cfg or ls /boot/grub/

vmlinuz

(hdX,Y)/ or /

ls (hdX,Y)/vmlinuz or ls /vmlinuz or ls /

linux-3.2.0-14*

(hdX,Y)/boot/ or /boot/

ls (hdX,Y)/boot/vmlinuz-3.2.0-14

initrd

(hdX,Y)/ or /

ls (hdX,Y)/ or ls /initrd

initrd.img-3.20-14

(hdX,Y)/ or /boot/

ls (hdX,Y)/boot/initrd.img-3.20-14 or ls (hdX,Y)/boot/

* Note: Use the full kernel name, including -generic, when searching or setting a kernel variable. Using the «TAB completion» technique may eliminate some typing and be more accurate if available.

Use the following commands to set these parameters (if incorrect). Substitute the correct value for X and Y. (Example: set root=(hdX,Y) becomes set root=(hd0,5) )

Task

Command

Notes

Set the prefix

set prefix=(hdX,Y)/boot/grub

Use the actual location of the grub folder

Set root

set root=(hdX,Y)

Set the kernel

linux /vmlinuz root=/dev/sda1 ro

Set the kernel if the symlink vmlinuz exists in /

Set the kernel

linux (hdX,Y)/boot/vmlinuz-3.0.2-14 root=/dev/sda1 ro

Set the kernel itself

Set the initrd image

initrd /initrd.img

Set the initrd image if the symlink exists in /

Set the initrd image

initrd (hdX,Y)/boot/initrd.img-3.0.2-14

Set the initrd image itself

Specific Troubleshooting

Use the section below based on the type of GRUB 2 terminal prompt displayed on the monitor.

important.png The commands which follow assume you have determined the proper parameters for prefix, root, linux, and initrd. Review the Search & Set section of this page for guidance .

grub>

Terminal Display: The GRUB 2 header/version information and a grub> prompt.

  • g2_grub>.png

If GRUB 2 leaves you at the grub> prompt, it has normally found the grub folder and loaded at least some basic modules. The configuration file (grub.cfg) may be missing, misnamed, or corrupted.

Quick Fix:

  • Use the Search & Set section to confirm the correct paths are set. Inspect the contents of the /boot/grub folder. Look for the grub.cfg file. It could be misnamed or missing. If not located in /boot/grub, use the ls command look for another .cfg file or look in /boot or other locations. If you locate the correct .cfg file:

  1. configfile /boot/grub/grub.cfg or configfile (hdX,Y)/boot/grub/grub.cfg

    If a .cfg with another name is located, substitute its path/filename in the command.

    If the configuration file is loaded and not corrupt, when the above command is executed the GRUB 2 menu should appear and the user can make a selection to boot. Once booted into the system, correct the filename or move the configuration file to its proper location. Run update-grub. If the configuration file is not found, a message will be generated and the user must enter the boot commands manually.

Extended Fix:

The following commands should set the root and prefix paths and load the kernel and initrd image. With this information, GRUB 2 does not need a configuration file and should be able to boot the system if the only problem was a corrupted or missing menu.

  • Press ENTER after completing each line. Some entries will not provide feedback. This is normal.

  • If a «file not found» or similar error message is displayed while running these commands, ensure you are using the correct X,Y values and the correct paths are set.

1. set root=(hdX,Y)

Confirm the correct X,Y values and press ENTER.

Example: If the Ubuntu system is on sda5, enter: set root=(hd0,5)

2. linux /vmlinuz root=/dev/sdXY ro

Example: linux /vmlinuz root=/dev/sda5 ro

If the vmlinuz symlink does not exist, use the full path to the kernel in /boot

Example: linux /boot/vmlinuz-3.2.0-14-generic root=/dev/sda1 ro

If successful, after ENTER there will be a slight delay and no messages.

  • Wubi users only — substitute these commands in Steps 1 and 2:

  • 1.set root=(loop0)

    2. linux /vmlinuz root=/dev/sdXY loop=/ubuntu/disks/root.disk ro

3. initrd /initrd.img

Selects the latest initrd image.

If the vmlinuz symlink does not exist, use the full path to the initrd image in /boot

If successful, after ENTER there will be a slight delay and no messages.

4. boot

Boot to the latest kernel on the selected partition.

If the system fails to boot:

  1. Attempt to find the GRUB 2 configuration file. The normal name is grub.cfg file. If not found, look for a misnamed .cfg file or in alternate locations. The menu configuration file may contain settings required for a successful boot (such as non-standard kernel options) even if the paths/filenames are correct.

    1. Use the set command to confirm the correct root and prefix settngs. Also inspect the folders’ actual contents with the ls command. The grub prompt normally means the GRUB 2 folder is intact but doesn’t guarantee the integrity of other system files.

    2. root= should point to the drive and partition on which Ubuntu is installed. If you use the ls / command you should see the main Ubuntu system folders.

If the system boots, please refer to the [[#Post-Boot Follow Up|Post Boot Follow Up] section

If the system fails to boot, proceed to the [#grub rescue|grub rescue]] section for more detailed troubleshooting options.

grub rescue>

The GRUB 2 rescue mode is a major enhancement to the GRUB bootloader. The presence of the grub rescue> prompt signifies that GRUB 2 has failed to find the grub folder, the grub.cfg file, and/or the associated modules. The rescue prompt is presented so the user can provide the path to the grub folder, load the necessary modules, and provide the proper boot commands.

  • g2_grub_rescue.png

A common reason for the grub rescue> prompt is an incorrect path to the grub folder. Reasons for the prompt also include a failure to update GRUB 2 after certain system or partition operations, improper designation of the grub folder location, missing linux or initrd.img symlinks in /, or a failed installation.

To successfully boot from the grub rescue> prompt:

  • The grub folder must exist and contain the necessary GRUB 2 files and modules.

  • The proper paths must be set via the set prefix command.

    • Many GRUB 2 commands will not work until the correct path is set.

      If the path to the grub folder (normally /boot/grub) is not correct, an unknown command or file not found message is likely.

  • The necessary modules must be loaded.
    • The kernel cannot be loaded until the ‘linux’ module is loaded.
  • A Linux kernel and initrd.img must be located and loaded.

Use the General Troubleshooting Preparation section to locate the correct partitions and file locations. Once the user has confirmed the paths and existence of the proper folders using the Search & Set section, run the following commands:

1. set prefix=(hdX,Y)/boot/grub

Use the values determined earlier.

Example: If the Ubuntu system is on sda5, enter: set prefix=(hd0,5)/boot/grub

2.* set root=(hdX,Y)

Confirm the correct X,Y values and press ENTER.

Example: If the Ubuntu system is on sda5, enter: set root=(hd0,5)

3. insmod normal

Load the normal module.

If the module loads there will be no message.

If the module fails to load, try the full path: insmod (hdX,Y)/boot/grub/normal.mod

4. normal

Transition to the normal GRUB 2 mode with increased functionality.

If the module loads there will be no message.

If the module loads, HELP, TAB completion and command recall using the UP/DN keys should be available.

5. set

(Optional) Review the current settings.

6. insmod linux

Load the linux module. An error message usually means the path is incorrect.

7.* linux /vmlinuz root=/dev/sdXY ro

Selects the latest kernel.

Example: linux /vmlinuz root=/dev/sda5 ro

If the vmlinuz symlink does not exist in /, use the full path to the kernel in /boot

Example: linux /boot/vmlinuz-3.2.0-14-generic root=/dev/sda1 ro

8. initrd /initrd.img

Selects the latest initrd image.

If the initrd symlink does not exist in /, use the full path to the initrd image in /boot

If successful, after ENTER there will be a slight delay and no messages.

9. boot

Boot to the latest kernel on the selected partition.

  • * Wubi users only — substitute these commands in Steps 2 and 7:

  • 1.set root=(loop0)

    2. linux /vmlinuz root=/dev/sdXY loop=/ubuntu/disks/root.disk ro

Some additional considerations:

  • The current prefix and root settings may be checked at any time with the set command. To remove a setting, use the unset command.

    • Example: unset prefix

  • Modules must be loaded before they can be used. If a module has not been loaded a unknown command error is displayed. If an incorrect path is specified, a file not found error message may be displayed.

  • The linux module must be loaded to be able to load both the kernel and the initrd image unless the normal module is loaded first.

  • If the modules cannot be found in the /boot/grub folder, the user may be able to load them from the /usr/lib/grub/i386-pc folder. The address if Ubuntu was installed on sda1 would be (hd0,1)/usr/lib/grub/i386-pc and the command would be:

    • insmod (hd0,1)/usr/lib/grub/i386-pc/normal.mod

Refer to the Post Boot Follow Up section if the system successfully boots.

GRUB

Presence of the word GRUB at the top left of the monitor with no blinking cursor indicates that GRUB 2 can not even find the Master Boot Record (or equivalent) information. Thus, the core.img file, the /boot and /grub folder locations and contents are completely unknown to GRUB 2.

  • g2_grub_fail.png

The seriousness of the problem cannot be assessed without the use of another operating system or an Ubuntu LiveCD or equivalent. The Ubuntu partition should be mounted for inspection and the user can then check to see if the system files are intact. If so, the user can use the »ChRoot» procedure from the LiveCD to reinstall GRUB 2 and rewrite the information to the MBR.

Details on this procedure are contained in the Grub2/Installing community documentation.

Following a failed boot, GRUB 2 is designed to display the GRUB 2 menu on the next boot and await user input. This will happen even if the user has set the system to boot without displaying the GRUB 2 menu. This provides the user the opportunity to select a different menu option or edit a menuentry to change boot parameters. While this can cause problems on a server, for most users it is a benefit which will prevent constant rebooting during unmonitored operations.

  • g2_grub_edit_menu.png

In addition to its troubleshooting benefits, pre-boot editing of the GRUB 2 menu also allows users to add or remove kernel options, change operating modes, and accomplish other tasks such as testing fonts and splash images. For users who like to experiment, the settings altered via the GRUB 2 terminal are non-persistent and won’t affect future boots.

  • If the menu is displayed, the automatic countdown may be stopped by pressing any key other than the ENTER key.
  • If the menu is not normally displayed during boot, hold down the SHIFT key as the computer attempts to boot to display the GRUB 2 menu.
    • In certain circumstances, if holding the SHIFT key method does not display the menu pressing the ESC key repeatedly may display the menu.
  • Press the ‘e’ key to reveal the selection’s settings.
  • Use the UP/DN/Left/Right cursor keys to navigate to the desired point for editing.
  • Make a single or numerous changes at any spot in the menu. Do not use ENTER to move between lines.

  • TAB completion is available, which is useful in entering kernel and initrd entries.

    • After starting to type the kernel or initrd name, press TAB.
    • If additional characters are not added, look at the bottom of the menu as there may be multiple choices. Add characters until only one entry is visible at the bottom, then TAB again.
  • When editing is complete:
    • CTRL-x or F10 — boot with the changed settings (highlighted for emphasis).

    • CTRL-c or F2 — jump to the command line to perform diagnostics, load modules, change settings, etc.

      • If an edit is incomplete and GRUB 2 detects an error in the kernel or initrd line it will return to the line when exiting this mode.

    • ESC — Discard all changes and return to the main menu.

    • The choices are listed at the bottom of the screen as a reminder.
  • Edits made to the menu in this manner are non-persistent. They remain in effect only for the current boot.
    • Once successfully booted, the changes can be made permanent by editing the appropriate file, saving the file, and running update-grub as ‘root’.

  • Change a kernel version if one is available but not listed on the GRUB 2 menu.
    • Use the TAB key after entering part of the kernel or initrd version to see which ones are available.

  • Add or remove kernel options from the linux line.

    • Remove quiet to display system messages during boot.

    • Remove existing options and add nomodeset to avoid module loading, especially if having video issues.

  • Boot to the recovery mode even if it is not listed on the menu.
    • Remove existing kernel options from the linux line and add single

  • Remove references to UUIDs
    • Remove the entire search line

    • On the linux line, replace «root=UUID=<some alphanumeric>» with «root=/dev/sdXY»

Post Boot Follow Up

Any changes made from the GRUB 2 terminal are not permanent. After successfully booting into the system the user must take several steps to ensure the problem is permanently fixed.

  1. Update the GRUB 2 configuration file
    • sudo update-grub

  2. Reinstall GRUB 2 to the drive’s MBR or equivalent

    • Install to the drive, not to the partition. Example: sda, not sda1

      sudo grub-install /dev/sdX  

  3. Inspect the GRUB 2 configuration file. The default is /boot/grub/grub.cfg

    • For problems with booting the main linux kernel, verify the search, linux, and initrd lines in the [### BEGIN /etc/grub.d/10_linux ###] section of the file.

      • Ensure the paths and kernel/initrd image versions are correct.
      • Confirm the UUID numbers.
      • UUIDs can be checked with the sudo blkid command.

  4. Verify the existence and contents of the system boot folders.
    • / should contain the symlinks vmlinuz and initrd.img

    • /boot/ should contain the actual kernel (vmlinuz-X.X.X-XX…) and initrd image (initrd.img-X.X.X-XX…)

    • /boot/grub should contain grub.cfg and numerous module files (*.mod)

For a corrupted GRUB 2 installation, purging and reinstalling GRUB 2 is very easy if the user has a working Internet connection. Refer to Grub2/Installing#Purging & Reinstalling GRUB 2 for guidance.

Fallback mode

It is possible to configure Grub2 to fall back to a known good menu-entry if the default menu-entry for some reason fails to boot. An example script that can be used for this is available at this webpage (in German).

GRUB 2 Errors

GRUB 2 does not report error numbers. If a number is associated with an error, it is a problem with the transition from GRUB legacy to GRUB 2.

A GRUB 2 error will leave the user at the grub> or grub rescue> prompt, the word GRUB with no cursor, or a hung boot caused by improper system path designations or a corrupted operating system. These issues are addressed earlier on this page — go to the General Troubleshooting Preparation section to start the recovery process.

Selected Problems and Bugs

External Drive Installs and »grub-pc» Updates

Launchpad Bug 496435 Installs of Ubuntu on external drives can cause problems as grub-install uses device names (e.g. sda, sdb) rather than UUIDs in certain circumstances. If connected to another machine when an update of grub-pc is made, the upgrade may be written to the incorrect device and make the computer unbootable.

A workaround is posted on the bug link above.

External Drive Installs and MBR Selection

Launchpad Bug 414996

When installing Ubuntu to a USB drive, the potential exists for GRUB 2 to write to the hard drive’s MBR or split the installation between the hard drive and the USB drive (rather than completely on the USB device). This can render the main drive unbootable.

Workaround: During the final stages of the install there is an «Advanced» button which allows the user to select the install location. See the bug report for more details.

Boot Partition is in Logical Volume whose Volume Group contains a snapshot

Launchpad Bug 563895

When your boot partition (the one providing /boot) is a LV, make sure not to have any LVM snapshots inside the containing VG. At reboot this will render your system unbootable, dropping you in a «grub rescue>«-shell with the following message: «error: no such disk.»

The grub-rescue-shell provided does not help you, because all modules (esp. lvm) are unreachable. You’ll have to boot from a install medium and remove all snapshots that are in the same VG as your boot partition by hand.

This issue is extremely annoying if your server is in a remote datacenter since the origin of the problem cannot be spotted easily and repairing the system may be hard.

While this will be fixed in the upcoming Maverick Meerkat 10.10 release, the current Lucid Lynx LTS 10.04 is affected.

A workaround would be to install ubuntu using a separated non-LVM partition for /boot if you are using LVM snapshots regularly.

There’s some kind of irony that if you’re careful and take a LVM snapshot before upgrading (and possibly rebooting) your system, this will trigger the bug.

insmod fails with «error: no such disk»

Several grub2 modules, such as the linux-module depends on other modules, which is attempted to be auto-loaded. For this to work, the variable $prefix, must be set to where the grub2 modules can be found. Usually, this is accomplished with the command «set prefix=/boot/grub«.

Links

Grub2

Grub2/Displays

Grub2/Installing

Grub2/Submenus

Grub2/Upgrading

Boot-Repair


CategoryBootAndPartition

The objective of this article is to list problems and errors that may occur in certain situations when using the GRUB Legacy bootloader. All these solutions have been acquired through the cooperation of users on the Gentoo Forums.

Starting notes

Acknowledgements

Many thanks to Earthwings, penetrode, loyaltonone, pilla, airhead, nephros, yamakawa and all the others for the suggestions on the original thread.

Disclaimer warning

The examples provided are just examples. Be sure to change partition numbers and the like according to the specific systems specs. Follow the solutions provided by this document at the readers own risk.

GRUB loading, please wait…

Situation

GRUB loading stage 1.5
GRUB loading, please wait...

After this message, the system stops. If attempting to boot the system using a GRUB floppy, the problem disappears.

Solution

According to The_Bell, changing the boot order in the BIOS can solve the problem.

Tell the BIOS to not boot from the floppy first.

[1] took hard disks off the system one-by-one until found out the problem was caused by the SiI3512A SATA RAID-controller.

penetrode wrote that this may also be due to bad CFLAGS settings. Although the current GRUB ebuild filters out-fstack-protector, it can’t hurt to recompile GRUB with clean CFLAGS if nothing else helps.

root #CFLAGS="-O2 -march=i686 -fomit-frame-pointer -pipe" emerge grub:0 --ask

This problem appeared on a dell r320 server, caused by having serial and terminal options in grub.conf, problem disappeared after removing those options.

FILE grub.confoptions to remove

#serial --unit=1 --speed=19200  
#terminal --timeout=10 serial

GRUB Error 12

Situation

12 : Invalid device requested.

This error is returned if the device strings syntax is correct but other than that, an error occurred that isn’t defined by any other error.

Solution

When GRUB was installed in the boot record using the interactive commands, were the two lines below executed in the GRUB prompt?

grub>root (hd0,0)

grub>setup (hd0)

(hd0,0) must be replaced with the boot partition and (hd0) with the HDD that was chosen. Remember that (hd0) will install the bootloader in the Master Boot Record of the first hard disk, the primary master.

GRUB error 15

Situation

This error can occur in two different stages of the GRUB configuration, either during the initial configuration (installing GRUB in the master boot record) or after booting the system and attempting to launch Linux (or any other entry).

Initial configuration:

grub>root (hd0,0)

 Filesystem type is xfs, partition type 0x83

grub>setup (hd0)

 Checking if "/boot/grub/stage1" exists... no
 Checking if "/grub/stage1" exists... no

Error 15: File not found

Booting an entry:

Booting 'Gentoo Linux'
  
root (hd0,0)
Filesystem type is ext2fs, partition type 0x83
kernel (hd0,0)/boot/kernel-2.4.20 root=/dev/sda3 vga=792
  
Error 15: File not found
Press any key to continue...

Solution — Initial configuration

This error is returned if the specified file name cannot be found, but everything else (like the disk/partition info) is OK.

Frequently, the error notes a missing kernel image file. Make sure that the file it is referring to exists on the boot partition.

To find out the exact name of the kernel, boot from the installation cd, mount the root and (if applicable) boot partition. Next, chroot into the Gentoo system and do a listing of the available files to see what kernel images there are available:

This will list all the kernels that there are on the boot partition. If the kernel is missing make sure to have compiled a kernel (using genkernel or manually):

root #cd /usr/src/linux/

root #make menuconfig

root #make

And that it has been copied to the boot partition:

root #cp /usr/src/linux/arch/i386/boot/bzImage /boot

Verify that the name of the kernel is exactly the same as the one mentioned in the grub.conf file. Also make sure that the kernel line in the grub.conf file is referring to that partition (either explicitly or implicitly).

Another reported mistake is to have the BIOS ignore the disk on which the kernel or GRUB stages reside. Also, the partition on which GRUB stores its stages should not use a software RAID-5 (or other striping technology) configuration.

Solution — Booting an entry

First, verify that the root and setup lines that were used are correct.

If it is certain they are valid, then there is the possibility of using a flawed GRUB version (0.93.20031222). Upgrade the Portage tree or mask this version of GRUB:

root #echo "=sys-boot/grub-0.93.20031222" >> /etc/portage/package.mask

root #emerge --ask sys-boot/grub:0

Another option is using the grub-install script as is recommended by the GRUB authors. The --root-directory option is needed if there is a separate boot partition, otherwise it should be left out.

root #grub-install --root-directory=/boot /dev/sda

When all this fails, the boot partition may be corrupt. Check the partition for errors:

GRUB error 17

Situation

root (hd0,0)
filesystem type unknown partition type 0x7
  
Error 17 : Cannot mount selected partition

Solution

This error is returned if the partition requested exists, but the filesystem type cannot be recognized by GRUB.

Be sure to check the root(x,y) settings in grub.conf.

Also, when trying to boot Windows, make sure that the grub.conf file has the root (hdX,Y) (or rootnoverify (hdX,Y) ) and chainloader (hdX,Y)+1 in it.

GRUB error 18

Situation

kernel (hd1,4)/bzImage root=/dev/sdb7
  
Error 18: Selected cylinder exceeds max supported by BIOS

Solution

This error is returned when a read is attempted at a linear block address beyond the end of the BIOS translated area. This generally happens if the disk is larger than the BIOS can handle (512 MB for (E)IDE disks on older machines or larger than 8 GB in general).

Try an update for the BIOS and/or move the boot partition to the front (or at least into the appropriate range).

GRUB GRUB GRUB GRUB GRUB …

Situation

GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB
  GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB GRUB
...

Solution

According to airhead this can be caused by having the BIOS detect the disks automatically. Try to set the BIOS entry to User Type HDD.

Another possibility is that Grub was installed on the MBR and then reinstalled (for instance due to hard disk changes) but using the wrong setup and root commands.

Probing devices to guess BIOS drives. This may take a long time

Situation

While trying to install GRUB, it hangs after displaying the following line:

root #grub

Probing devices to guess BIOS drives. This may take a long time.

Solution

One reported cause was an exotic configuration of disk devices, like ultra/non-ultra DMA disks on one cable.

When installing GRUB, it just hangs

Situation

When installing GRUB, it hangs:

At this stage, the installation stops.

Solution

If there is no floppy drive, was the --no-floppy switch used?

Uncompressing Linux… Ok, booting the kernel

Situation

The system hangs after displaying the following line:

Uncompressing Linux... Ok, booting the kernel.

Solution

Strictly speaking, this is no GRUB error. One possible cause is that ACPI is not working correctly but is enabled in the kernel. Try to disable it in the BIOS or in the kernel. Another possible cause is that the kernel has been compressed to a format it does not support for decompression, such as LZO requiring LZO_DECOMPRESS.

GRUB just shows a GRUB prompt

Situation

When booting the system, a GRUB prompt appears instead of a list of entries that were defined in the grub.conf file.

Solution

Mount the boot partition and verify if the grub/grub.conf file exists.

root #mount /dev/sda1 /mnt/gentoo/boot

root #cat /mnt/gentoo/boot/grub/grub.conf

Also make sure that the menu.lst symbolic link exists:

root #ls -l /mnt/gentoo/boot/grub/menu.lst

lrwxrwxrwx  1 root root 9 Mar  7 14:00 /mnt/gentoo/boot/grub/menu.lst -> grub.conf

If not, recreate the symbolic link:

root #cd /mnt/gentoo/boot/grub

root #ln -snf grub.conf menu.lst

If this is the case, reinstall GRUB:

(chroot) #grub-install --root-directory=/boot /dev/sda

Could not find device for /boot/boot: not found or not a block device

Situation

When running grub-install during the GRUB installation, the following error appears:

root #grub-install --root-directory=/boot /dev/sda

Could not find device for /boot/boot: not found or not a block device

Solution

Check that the following wasn’t forgotten:

root #grep -v rootfs /proc/mounts > /etc/mtab

Situation

After hitting the Enter (Return) key at the GRUB menu during the system boot, the system reboots.

Solution

Try disabling framebuffer support in the kernel. If this does not help, disable APM and ACPI.

Situation

After hitting Enter (Return) at the GRUB menu during system boot, the screen blanks out, but the system is responsive (for instance, the numlock LED is switchable).

Solution

Turn off framebuffer (typically remove vga=XYZ from grub.conf) and check the processor architecture in the kernel config.

Missing GRUB image

Situation

When booting the system, the spiffy Gentoo splash screen is not seen.

Solution

First of all check if the splash screen file that is being are referred to in grub.conf really exists. If that is the case, go and check the GRUB ebuild. Maybe the patch for the splash image is commented out in the version that is being used.

Failing To boot Windows from a second hard drive

Situation

After selecting the Windows entry, the system refuses to boot without any clear reason as to why.

Solution

cyrillic provides information that it is possible to «map» the disks in a different order by changing grub.conf‘s Windows entry like so:

FILE grub.confMapping disks

title Windows XP
  map (hd0) (hd1)
  map (hd1) (hd0)
  chainloader (hd1,0)+1

GRUB segfaults when trying to install

Situation

The situation described below is only relevant for grub-0.95.x at the moment of installing GRUB at the boot sector.

grub>root (hd0,0)

grub>setup (hd0)

Segmentation fault

Solution

This is a known bug related to this problem and has been fixed in grub-0.96. It is also known that grub-0.94-r1 and grub-0.94-r2 should work correctly. If that fails too, try to emerge grub-static which is currently stable on amd64 and unstable on x86 and (~x86). Check out bug #79378 for additional information.


This page is based on a document formerly found on our main website gentoo.org.
The following people contributed to the original document: Hartwig Brandl, Ioannis Aslanidis
They are listed here because wiki history does not allow for any external attribution. If you edit the wiki article, please do not add yourself here; your contributions are recorded on each article’s associated history page.

When you boot your computer, you might find that your computer is stuck in Grub Loading Error 15, 17, 21, or 22. Do you know what they are, the causes of these GRUB Load Errors, and how to fix them to make your computer go back to normal? This MiniTool article shows you the answers.

What Is GRUB Loading Error?

GRUB, which is also known as GNU GRUB, stands for GNU GRand Unified Bootloader. It is a boot loader package from the GNU Project. It provides you a choice to boot one of multiple operating systems installed on a computer or choose a specific kernel configuration available on a particular operating system’s partitions.

It is similar to NTLDR or BOOTMGR on Windows. But, it supports both Windows and Linux kernels and has more features. You need to configure GRUB properly when using your computer. If not, you might encounter different kinds of GRUB errors like Grub Loading Error 15, 17, 21, 22….

Tip: If you encounter the BOOTMGR is missing issue, you can refer to this article to solve it: 11 Solutions to «BOOTMGR Is Missing» Error in Windows 10/8/7; If you are facing NTLDR is missing issue, you can read this post to get the solutions: 10 Solutions to Fix NTLDR Is Missing in Windows 10/8/7.

Now, we will introduce these common GRUB Loading Errors in the following content.

Common Grub Loading Errors

Usually, there are no error codes in Grub Stage 1. You might just receive the error message saying Hard Disk Error, Floppy Error, Read Error, or Geom Error. The GRUB loading error code always appears in Grub Stage 1.5 or Stage 2.0.

There are 4 common GRUB Loading Errors:

  1. Grub Loading Error 15: File not found. This GRUB Loading Error always appears when a specified file name cannot be found by the system.
  2. Grub Loading Error 17: Cannot mount selected partition. This GRUB Loading Error always appears when the required partition exists, but the type of file system is not recognized by GRUB.
  3. Grub Loading Error 21: Selected disk does not exist. This GRUB Loading Error always appears when the disk is not recognized by the BIOS in the system.
  4. Grub Loading Error 22: No such partition. This GRUB Loading Error always appears when a required partition is not on the selected disk.

Top Reasons for GRUB Loading Errors

Why do the GRUB Loading Errors occur when you boot your computer? Here, we collect some reasons and show them as follows:

  • The configuration of GRUB is improper.
  • GRUB is installed in a wrong location.
  • GRUB is deleted by mistake.
  • mbr is corrupted.

Now, you know what GRUB is, the common GRUB Loading Error codes, and the top main causes of these errors. Then, if you are bothered by the GRUB Loading Error, you must want to get rid of it immediately because you still need to use your computer to deal with your work. Keep reading to get the solutions.

How to Fix GRUB Loading Errors?

Focusing on these 4 GRUB Loading Errors, we will introduce 4 different solutions. You just need to select a suitable solution according to the error code you receive.

How to Fix GRUB Loading Errors?

  1. How to fix GRUB Loading Error 15?
  2. How to fix GRUB Loading Error 17?
  3. How to fix GRUB Loading Error 21/22?

How to Fix GRUB Loading Error 15?

If you are bothered by Grub Loading Error 15, you need to make sure that the kernel file exists on your computer. Here, you need to shut down your PC and then boot it from the live CD. Then, you can mount /boot on your partition and then do the following: cd /boot | ls to check the exact name of the kernel file.

It is quite possible that the kernel file is missing from your computer. If so, you can still use the live CD to perform a system reinstallation to get rid of the issue.

How to Fix GRUB Loading Error 17?

If you are facing Grub Loading Error 17, you need to make sure that your root(x,y) settings are right in your Grub.conf. You still need to use a live CD to set up Grub as follows:

1. Boot your computer from a live CD.

2. Execute this command: sudo fdisk –l.

3. You are likely to get the following results:

Disk /dev/sdb: 500.1 GB, 500107862016 bytes

255 heads, 63 sectors/track, 60801 cylinders, total 976773168 sectors

Units = sectors of 1 * 512 = 512 bytes

Sector size (logical/physical): 512 bytes / 4096 bytes

I/O size (minimum/optimal): 4096 bytes / 4096 bytes

Disk identifier: 0x62ff371f

Device Boot Start End Blocks Id System

/dev/sdb1 2048 206847 102400 7 HPFS/NTFS/exFAT

/dev/sdb2 206848 174082047 86937600 7 HPFS/NTFS/exFAT

/dev/sdb3 174082110 976771071 401344481 f W95 Ext’d (LBA)

Partition table entries are not in disk order.

The cause of the problem appears on the last line: Partition table entries are not in disk order.

4. You can fix the problem by executing the following command: sudo fdisk /dev/hda. hda means the whole hard disk.

5. If you are an expert, you can select x and press Enter. If you are not an expert, just skip to the next step.

6. Select f and press Enter to fix the partition order.

7. Select w and press Enter to write table to disk.

8. Then, you need to finalize these command one by one in GRUB:

sudo grub

root (hd0,1)

setup (hd0)

quit

Here, (h0, 1) stands for the first hard drive and the second partition on that drive.

Of course, the above hd0,1 and hd0 are just examples. You need to know which hard disk houses your OS and then replace the numbers according to your actual situations.

When all these steps are done, you can restart your computer to check whether it can work as normal.

How to Fix GRUB Loading Error 21/22?

If you are bothered by GRUB Loading Error 21/22, you can follow these steps to fix the problem.

  1. Boot your computer from the live CD.
  2. Open a terminal and then run sudo grub. This can lead you to a GRUB command line.
  3. Run find /boot/grub/stage1.
  4. Then, run root (hd0, 1). Here, (h0, 1) stands for the first hard drive and the second partition on that drive. You can replace these two numbers according to your own situation.
  5. Next, run setup (hd0).
  6. At last, run quit to complete the operation.

After these 6 steps, you still need to reboot your computer to see whether the GRUB Loading Error 21 or GRUB Loading Error 22 is disappeared.

Click to Tweet

If You Lose Your Data Due to GRUB Loading Errors

After the GRUB Loading Errors are solved, you can use your computer as usual. However, you may find that some important files are missing from your device by accident due to the error. In a situation like this, you can use a professional data recovery software to get back your data. Here, we suggest using MiniTool Power Data Recovery.

This free file recovery tool is specially designed to rescue your lost and deleted files from your computer hard drives, SD cards, memory cards, pen drives, CDs, DVDs, and more. It has 4 recovery modules that are designed for different situations.

For example, if you want to recover data from a partition on the hard drive, you can use the This PC module. But, if you have repartitioned the hard drive after missing files, you’d better use the Hard Disk Drive module because it enables you to scan the entire drive at once.

This software is designed for Windows computers. However, if your computer is dual-boot (Windows and Linux), you can choose to recover your Linux data under Windows.

MiniTool Power Data Recovery has a trial edition and you can use it to scan the drive that has saved your lost files and then check whether it can find the files you want to restore. If you are interested in it, you can press the following button to download and then install it on your computer to have a try.

Free Download

After installing MiniTool Power Data Recovery on your device, you can use these steps to retrieve your data.

1. Open this software and you will enter the This PC interface directly.

2. Suppose that you want to recover data from a partition, you can just stay at this recovery module. Then, you need to select the target partition and press Scan to start the scanning process.

select the target partition to scan

3. The whole scanning process will last for a while. To make sure that you can get the best data recovery effect, you need to wait until the whole process ends. Then, this software will show you the scan results by path.

Here, you can click each path and unfold the folders in it to find your needed files. However, you may find that it is not easy and fast to find the target items using this method. If so, you can use other features of this software to perform a quick search.

For example:

  • Type: The Type feature can enable the software to show the scan results by type. You must know which type of data you want to recover. So, you can select that type to find your needed files quickly.
  • Show Lost Files: After scanning, this software will show you all the data on the drive including existing and deleted files. If you only need to restore the deleted files, you can use this feature to make the software only show you the lost files. This can narrow down the search range.
  • Find: If you still remember the name of the file you want to recover, you can use this feature to directly locate that file. However, if the name of the file is damaged, you will be unable to use this method to find your data.
  • Preview: This feature enables you to preview up to 70 types of files. So, if you are not sure whether it is the file you want to restore, you can just preview it to make a confirmation.

Type, Show Lost Files, Find, and Preview

4. You are not allowed to use this trial edition to recover the scanned files. However, you can update this software to a full edition and then recover your needed files without limits. If you are a personal user, the Personal Ultimate edition can fully meet your need and you can even enjoy a lifetime free update.

Here, you need to know that you should not select the files’ original path to save these data. Otherwise, the deleted files will be overwritten and become unrecoverable.

Click to Tweet

Bottom Line

Now, you should know what GRUB is, the GRUB Loading Errors you may encounter when booting your PC, and how to get rid of these errors. At the same time, we also recommend a data recovery software for recovering your lost and deleted files that are caused by these GRUB Loading Errors. We hope this article is helpful to you.

Should you have any related issues, you can contact us via [email protected] or let us know in the comment.

GRUB Loading Error FAQ

What is a GRUB Loading Error?

A GRUB Loading Error always happens when you boot the computer. It can be caused by improper GRUB configuration, a wrong location of GRUS, missing GRUB, corrupted MBR, etc.

How do I fix grub loading errors?

There are different kinds of GRUB Loading Errors like GRUB Loading Error 15, 17, 21, and 22. This current article shows you the corresponding solutions. You can scroll up to find them.

How to fix Error No Such Partition Grub Rescue?

What Is GRUB

GRUB or GNU GRUB is short for GRand Unified Bootloader. It is a boot loader used on multi-OS computers that provides users the choice to choose which operating system to boot from on the computer. Different operating systems may need varying boot loaders. For example, NTLDR is the boot loader for Windows NT operating systems, and LILO is the boot loader for Linux. As for GRUB, it is the boot loader for Windows and Linux and is generally used on computers that are with both Windows and Linux installations.

Here’s a quick view of common GRUB loading errors and corresponding solutions. Jump to the part you’re most interested:

Workable Solutions Step-by-step Troubleshooting
Fix 1. GRUB Loading Error 15 boot from the Live CD, and mount/boot depending on your partition…Full steps
Fix 2. GRUB Loading Error 17 use a distribution CD or Live CD to set up Grub as sudo grub > root (hd0,0) > setup (hd0) exit…Full steps
Fix 3. GRUB Loading Error 21 Boot the computer from the Ubuntu installation disc > Run Command Prompt as an administrator…Full steps
Fix 4. GRUB Loading Error 22 Restart the computer and press «F8» until you see the options, go back to the menu…Full steps

Common GRUB Loading Errors

However, it’s not without a problem while using GRUB. Many users have the experience of encountering the GRUB loading error during the computer startup. There are two versions of GRUB, and if you’re using Stage 1.5 or Stage 2.0, you’ll probably encounter grub loading error 15, 17, 21, or 22.

GRUB loading error 15

File not found. This error is displayed when the specified file name cannot be found.

GRUB loading error 17

Cannot mount selected partition. This error is displayed when the partition requested exists, but the file system type is not be recognized by GRUB.

GRUB loading error 21

The selected disk does not exist. This error is displayed if the disk is not recognized by the BIOS in the system.

GRUB loading error 22

No such partition. This error is displayed if a requested partition isn’t on the selected disk.

What Causes GRUB Loading Error 15, 17, 21, 22

When you install Windows and Linux on a computer, you need to configure GRUB correctly to boot from one of the operating systems successfully. Or you may encounter GRUB loading errors, like error 15, 17, 21, and 22. The common GRUB loading errors might be caused by:

  • Improper configuration of GRUB
  • The wrong installation location of GRUB
  • Accidental deletion of GRUB
  • The corruption of MBR

How to Fix GRUB Loading Error 15, 17, 21, 22

The solutions differ based on the error you are faced with. Specify the error message you encounter and carry out the corresponding solution.

Fix GRUB Loading Error 15

Make sure the kernel exists. To find out what the exact kernel name is, boot from the Live CD, and mount /boot depending on your partition and then do the following: cd /boot | ls

Fix GRUB Loading Error 17

Make sure your root(x,y) settings are right in your Grub.conf. You could use a distribution CD or Live CD to set up Grub as shown below. (h0,0) means the first hard drive and the first partition on that drive.

sudo grub

root (hd0,0)

setup (hd0) exit

Fix GRUB Loading Error 21

Step 1. Boot the computer from the Ubuntu installation disc.

Step 2. Run Command Prompt as an administrator.

Step 3. Enter the following command:

$sudo -s
#grub
grub> find /boot/grub/stage1 (then cmd will return something like «hd0,0»)
grub> root (hd0,0)
grub> setup (hd0)
grub> quit

Fix GRUB Loading Error 22

Step 1. Restart the computer and press «F8» until you see the options.

Step 2. Go back to the menu where you can choose the operating system.

Step 3. Choose «Microsoft Windows Recovery Console». (You may need your Windows installation disc to access the recovery console.)

Step 4. If you are asked to choose the system drive, enter the number in front of the system drive listed.

Step 5. Enter the account password as required. Run the command fixmbr and enter «y» to confirm the operation.

Step 6. Enter «exit» and restart the computer.

How to Recover Data Lost After Fixing GRUB Loading Error

Applies to: Restore all lost files and data after fixing GRUB loading error in Windows 10/8/7.

Applying the fix for a specific grub loading error in Windows may cause data loss. For example, some operations would format the disk partition or delete hard drive contents. So it’s necessary to learn how to recover data after getting rid of the grub loading error on your computer.

Reliable EaseUS Data Recovery Wizard — EaseUS Data Recovery Wizard specializes in file recovery on all Windows operating systems. It allows you to recover data lost due to the GRUB loading error effectively in only a few simple clicks.

See how to recover the accidentally deleted or formatted hard disk data while fixing GRUB loading error on your computer with ease:

Step 1. Run EaseUS Data Recovery Wizard. Choose the drive where you lost files and start scanning. This software allows you to recover lost data from all devices, including HDD, SSD, USB drive, SD card, pen drive, camera, etc.

select a location to scan

Step 2. Browse the full scan results. You can choose the file type you need by clicking on the file type filter. EaseUS data recovery software supports 1000+ file types like photos, videos, documents, emails, audio files, and many more. 

Choose files to recover

Step 3. Select the files you want to preview. Click «Recover» and set a storage location to save the recovered data. 

Recover lost data

Besides, you can also apply this data recovery software to recover files and data lost on the desktop, laptop, internal hard drive, external hard drive, removable USB flash disk, pen drive, memory card, and many more storage devices.

The Bottom Line

GRUB loading errors always occur on computers with dual OS, and each error code is informative since it indicates what the possible cause is. Apply the solutions provided to cope with the issue and use EaseUS Data Recovery Wizard to retrieve the data when data loss happens.

Любите экспериментировать? Наверняка вы когда-либо пытались произвести какие-то действия со своей Linux-системой, причем не так важно какие были цели: изучение и познание новых возможностей или же какая-то более конкретная цель, в виде исправления той или иной ошибки. В любом случае, при работе с дистрибутивами Linux, для загрузки которых, в большинстве случаев, и используется Grub, с последним могут возникать неприятные проблемы, ввиду которых дальнейшая эксплуатация системы просто-напросто невозможна. В этой статье вы узнаете, что делать, если не загружается Linux. Как вести себя в подобной ситуации и какие действия производить, чтобы починить загрузчик Grub. Пожалуй, начнем.

GRUB_screenshot

Grub (или GRand Unified Bootloader) — загрузчик операционных систем с открытым исходным кодом. Распространяется он под лицензией GNU GPL, в полностью свободном виде. С помощью этого замечательного лоадера можно сделать много всего — основная же функция не ограничивается загрузкой лишь одной операционной системы. Вы можете иметь куда больше операционных систем на своем ПК, загружая любую из них с помощью Grub. На скриншоте выше вы можете видеть как примерно Grub выглядит. Кстати говоря, если вы захотите установить Ubuntu 18.04 рядом с Windows, вам определенно понадобится помощь Grub.

Grub используется в большинстве дистрибутивов Linux в качестве загрузчика по-умолчанию. Разумеется и с ним иногда возникают проблемы. Этим самые проблемы чреваты полным отказом операционной системы. Поэтому для починки Grub нам понадобятся дополнительные инструменты. Какие именно — узнаете далее.

От чего могут возникнуть проблемы

Одна из самых распространенных причин — это неправильный порядок установки двух операционных систем (Linux и Windows). Допустим, если вы захотите установить две этих операционных системы на свой ПК — вам непременно стоит знать правильную последовательность:

  • Сначала устанавливаем Windows
  • И только потом уже Linux

Если, например, сделать наоборот, то как раз-таки Grub будет поврежден; система будет грузиться напрямую в Windows, а дистрибутив Linux останется недоступным.

Grub может сломаться и по другим причинам. Например, из-за попыток ручного изменения параметров запуска (при недостатке опыта), в таком случае нужно будет либо вручную убирать лишнее, либо полностью переустанавливать Grub.

Восстановление Grub с помощью LiveCD/USB

Для этого способа нам понадобится флешка с дистрибутивом Linux на борту. Подойдет любой: от Ubuntu, Arch или даже Linux Mint. Здесь нужен только терминал, поэтому подойдет даже версия без графической оболочки.

Как создать LiveCD/USB

Само собой, нам понадобится носитель, на который мы временно (а может и нет) запишем систему. Сохраните все важные файлы, которые были на этом носителе, после чего (имеется ввиду на другом ПК, желательно под управлением Windows) запишите загруженный образ дистрибутива на носитель. В качестве примера мы будем использовать дистрибутив Ubuntu.

Идем на официальную страницу загрузки. Загружаем любую понравившуюся версию (лучше взять новейшую для десктопа), после чего записываем ее на USB/CD.

С помощью Rufus:

Последняя версия приложения доступна на официальном сайте. Сразу после загрузки и запуска/установки мы увидим такое окно:

Rufus

Вставляем носитель, выбираем его в соответствующем меню. Далее выбираем нужную схему раздела и тип системного интерфейса, и после уже открываем файловый менеджер с помощью этой кнопки:

Rufus obraz

Находим загруженный образ через менеджер, после чего жмем «Старт».

С помощью Etcher:

Опять же, идем на официальный сайт, где скачиваем последнюю версию утилиты. Далее делаем все так, как показано на этой гифке:

Etcher

Ну а теперь, собственно, можно переходить к восстановлению Grub. Вставляем флешку в наш ПК (где сломан загрузчик), после чего перезагружаем его с этой самой флешки. Как только мы войдем в лайв-систему, сразу открываем терминал, после чего проделываем следующие действия:

Открываем таблицу разделов с помощью команды:

sudo fdisk -l

Примерно такая таблица будет выведена на экран:

/dev/sda1 27 7683 66999082+ 83 Linux
/dev/sda2 * 8450 13995 45430855 7 HPFS/NTFS
/dev/sda3 11885 16574 6503497 5 Extended

По этой таблице мы видим, что Linux, в нашем случае, расположен на разделе /dev/sda1.

С помощью следующей команды мы смонтируем этот раздел в /mnt:

sudo mount /dev/sda1 /mnt

Теперь, для записи grub в MBR, нужно ввести следующую команду:

sudo grub-install --root-directory=/mnt /dev/sda

Если нужно только восстановить MBR диска (после переустановки Windows, к примеру), то этих действий будет вполне достаточно.

Если же необходимо обновить и меню grub (после установки Windows), то нужно выполнить еще и эту команду:

sudo update-grub --output=/mnt/boot/grub/grub.cfg

Вот и все, восстановление закончено!

Восстановление с помощью chroot

Помимо вышеописанного способа, при восстановлении Grub с помощью LiveCD можно использовать и этот. Тут мы будем использовать утилиту chroot.

Здесь нам, опять же, понадобится таблица разделов. Вводим уже известную команду:

sudo fdisk -l

В выводе снова будет эта таблица. Теперь нам надо присмотреться к ней еще внимательнее.

/dev/sda1 27 7683 66999082+ 83 Linux
/dev/sda2 * 8450 13995 45430855 7 HPFS/NTFS
/dev/sda3 11885 16574 6503497 5 Extended

В этом способе нам необходимо примонтировать системный, а также нескольких других важных разделов. Для этого вводим эти команды:

sudo mount /dev/sda1 /mnt
sudo mount --bind /dev /mnt/dev
sudo mount --bind /proc /mnt/proc
sudo mount --bind /sys  /mnt/sys

Обратите внимание, что если если разделы /boot или /var находятся отдельно, то Вам нужно будет примонтировать их в /mnt/boot и /mnt/var.

Далее мы переходим в окружающую среду chroot с помощью команды:

sudo chroot /mnt

И теперь, наконец-таки переустанавливаем Grub с помощью следующей команды:

grub-install /dev/sda

Если вы на этом этапе получаете какие-то сообщения об ошибках, то попробуйте использовать эти команды:

grub-install --recheck /dev/sda

или:

grub-install --recheck --no-floppy /dev/sda

Если все прошло успешно, выходим из chroot, используя команду:

exit

Далее нужно отмонтировать все разделы. Для этого вводим в терминал:

sudo umount /mnt/dev
sudo umount /mnt/proc
sudo umount /mnt/sys
sudo umount /mnt

В случае, если вы монтировали раздел /boot введите команду:

sudo umount /mnt/boot

Теперь перезагружаем систему с помощью:

sudo reboot

Можно также обновить меню Grub, используя команду:

sudo update-grub

Восстановление Grub в rescue mode

Если по каким-то причинам у вас нет доступа к LiveCD/USB-носителю, а также к компьютеру, с помощью которого этот самый носитель можно было бы сделать, то этот способ для вас.

Само восстановление проходит таким образом: сначала мы подгружаем все модули, чтобы открыть доступ ко всей функциональной части Grub, после чего запуститься с нужного раздела. Надо понимать, что Grub состоит из двух частей:

Одна из этих частей (первая) записана в MBR диска. В ней присутствует базовый функционал и ничего больше (консоль в rescue mode).

Стало быть, нам нужно определить, в каком разделе находится вторая часть Grub (находится в каталоге /boot/grub), и после чего подгрузить все недостающие модули. А вот уже после этого мы сможем запустить загрузчик с нужного раздела. В rescue mode есть всего четыре команды:

 ls
set
unset
insmod

Для начала вводим следующую команду:

 ls

В выводе будет что-то подобное:

(hd0) (hd0,msdos3) (hd0,msdos2) (hd0,msdos1) (hd1) (hd1,msdos2) (hd1,msdos1)

В некоторых случаях Grub неправильно опеределяет файловые системы находящиеся на разделах дисков. В данном примере загрузчик показывает их как msdos. Мы должны попытаться угадать диски, которые видим. В примере доступно два диска. Диск с индексом 0 содержащий три раздела, и диск с индексом 1 содержащий два раздела. Если вы знаете структуру своих дисков, определить нужный труда не составит.

В загрузчике Grub разделы нумеруются в обратном исчислении. Не очень ясно какой именно из разделов назван, к примеру (hd0,msdos3). Чтобы было более понятно, можно использовать вид (hd0,1). Если в грабе отсчет дисков идет с 0, а разделов с 1, то можно определить, что операционная система установлена в первый раздел первого раздела — (hd0,1). Используем следующую команду:

set prefix=(hd0,1)/boot/grub 
set root=(hd0,1)

С помощью этих команд мы приказываем системе использовать какой-то конкретный диск, для выполнения всех остальных операций (в нашем случае, это диск (hd0,1)). Чтобы проверить есть ли на данном диске загрузчик, введем эту команду:

ls /boot/grub

Если в выводе будет список файлов и папок, значит мы все сделали правильно. Теперь можно загрузить все необходимые модули. Для этого выполним команды:

insmod ext2
insmod normal
normal

После выполнения команд Grub загрузится в полнофункциональном режиме. Будут найдены все операционные системы, которые установлены на компьютере, после чего будет показано стандартное меню загрузки.

Чтобы закрепить результат (и не проделывать все то же самое после перезапуска ПК), нужно зайти в терминал своего дистрибутива Linux, где с root правами выполнить следующую команду:

grub-install /dev/sdX

sdX — диск, на который должен быть установлен Grub.

Если операционная система расположена на разделе с файловой системой btrfs, то нам необходимо выполнить следующие команды:

set prefix=(hd0,1)/@/boot/grub
set root=(hd0,1)

И подгрузить модули:

insmod btrfs
insmod normal

Ну и теперь запустить GRUB:

normal

Восстановление Grub с помощью утилиты Boot repair

1335260967

С помощью этой замечательной утилиты вы сможете восстановить загрузчик всего в пару кликов. Как видно из скриншота, утилита имеет собственный GUI, ее использование не вызовет трудностей.

Чтобы установить boot repair, вы можете воспользоваться одним из приведенных способов:

  • Запись и установка специального образа диска Boot Repair (и дальнейшая загрузка с него)
  • Установка Boot repair из PPA-репозитория в LiveCD/USB дистрибутиве.

Если с первым способом все понятно: нужно просто скачать и записать образ с помощью соответствующих инструментов. То во втором уже нужно знать конкретные команды, которые выглядят следующим образом:

sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt-get update && sudo apt-get install -y boot-repair

В утилите будет доступно два варианта на выбор:

Recommended repair исправляет большую часть известных ошибок, которые могли бы возникнуть при запуске. С его помощью вы сможете пофиксить и загрузчик Grub.

Create a BootInfo summary создает Boot-Info-Script – скрипт, который позволяет диагностировать большинство проблем при загрузке.

Здесь же есть и Advanced options. Он включает в себя варианты для восстановления и настройки загрузчика Grub2 (загрузка по-умолчанию, опции загрузки ядра, отображение или скрытие GRUB при загрузке, удаление GRUB). С помощью этих же инструментов, вы можете восстановить MBR и т.д.

Вам обязательно стоит заглянуть на официальный сайт Boot Repair. Там вы сможете найти более подробную информацию обо всех возможностях и особенностях программы. Там же будет доступна информация о выходе новых версий: фиксах и улучшениях самой утилиты, а также многом и многом другом.

Выводы

Вот мы и рассмотрели несколько вариантов исправления загрузчика Grub. Стоит сказать, что некоторые из них могут показаться сложными или даже невыполнимыми. Это не так, каждый из рассмотренных способов нашел подтверждение в виде сотен и тысяч актов исправления загрузчика Grub в опенсорсном сообществе. Кстати говоря, какой из способов выбрать — решать только вам, любой из них достаточно эффективен, чтобы попасть в этот материал.

Возможно вас заинтересуют и другие похожие материалы про починку загрузчика Grub2. Например, в этом материале вы узнаете, как починить GRUB2 если Ubuntu не хочет загружаться. Там более подробно рассказывается, как фиксить груб с помощью утилиты Boot Repair, возможно вам стоит заглянуть туда, если вы не поняли что-то из этого материала. Что же, ну а на сегодня это все. Надеюсь, что данный материал помог вам разобраться в ошибках. Что, в свою очередь, поможет вам их решить.

Introduction

The GRUB (Grand Unified Bootloader) is a tool for booting and loading operating system kernels and the default bootloader for systems based on the Linux kernel. Although it runs first when a machine is turned on, regular users rarely see GRUB in action. It functions automatically and requires no user input.

However, when attempting to boot another operating system alongside Linux on the same machine, the other system’s bootloader may overwrite GRUB, resulting in the inability of the Linux system to boot up.

This article will show you how to fix Linux boot failure using GRUB Rescue commands and the Boot Repair tool.

How to use Grub Rescue to fix Linux boot failure

Prerequisites

  • An account with sudo privileges.
  • Access to the command line.

Note: The tutorial below is written for GRUB 2, the current iteration of the GRUB bootloader.

GRUB Boot Issues

The most common reason for GRUB not booting into the operating system is another OS’s bootloader overwriting GRUB boot configuration. The problem occurs during an attempt a dual boot with an existing Linux installation. Another reason is the accidental removal of GRUB configuration files.

When GRUB is not able to boot the system, the GRUB Rescue prompt appears.

GRUB displaying "no such partition" error and the GRUB Rescue prompt.

The example above shows GRUB displaying the «no such partition» error before displaying the grub rescue prompt. Another common GRUB error is «unknown filesystem», followed by the same prompt.

GRUB displaying "unknown filesystem" error and the GRUB Rescue prompt.

Sometimes, the screen may show the grub prompt only.

GRUB displaying only the GRUB prompt.

GRUB Rescue Commands

Below is the list of the commonly used GRUB Rescue commands. Use the commands in the prompts mentioned in the previous section.

Command Description Example
boot Start booting (shortcuts: F10, CTRL + x). The command is issued without arguments.
cat Write the contents of a file to standard output. cat (hd0,1)/boot/grub/grub.cfg
configfile Load a configuration file. configfile (hd0,1)/boot/grub/grub.cfg
initrd Load the initrd.img file. initrd (hd0,1)/initrd.img
insmod Load a module. insmod (hd0,1)/boot/grub/normal.mod
loopback Mount an image file as a device. loopback loop0 (hd0,1)/iso/image.iso
ls Display the contents of a directory or partition. ls (hd0,1)
lsmod Display a list of loaded modules. The command is issued without arguments.
normal Activate the normal module. The command is issued without arguments.
search Search for devices. Option --file searches for files, --label searches for labels, --fs-uuid searches for filesystem UUID. search -file [filename]
set Set an environment variable. If issued with no arguments, the command prints the list of all environment variables and their values. set [variable-name]=[value]

Fixing Boot Failure

This tutorial covers two ways to resolve GRUB boot issues, using the GRUB Rescue prompt, and the Boot Repair tool.

Via Grub Terminal

1. Use the set command with no arguments to view the environment variables:

set

The example output shows that GRUB is set up to boot from (hd0,msdos3) partition:

The output of the set command in GRUB.

2. The ls command lists the available partitions on the disk.

ls

The output shows the partition list.

The output of the ls command in GRUB.

Use the ls command to find the partition containing the boot directory.

ls [partition-name]

The example shows the boot directory in the (hd0,msdos1) partition.

Finding the partition containing the boot folder in GRUB.

3. Set the boot partition as the value of the root variable. The example uses the partition named (hd0,msdos1).

set root=(hd0,msdos1)

4. Load the normal boot mode.

insmod normal

5. Start the normal boot mode.

normal

The normal mode enables you to issue more complex commands.

6. Load the Linux kernel using the linux command.

linux /boot/vmlinuz-4.2.0-16-generic root=/dev/sda1 ro

7. Issue the boot command.

boot

The system now boots properly.

Via Live image

Another way to fix your GRUB boot issues is to use a Linux live image to boot from an external device.

1. Download a live Linux installer. This example uses the Ubuntu 20.04 ISO image.

2. Use a tool such as Etcher to write the Linux image to an SD card or a USB flash drive.

3. Insert the bootable device and start the computer.

4. Select Try Ubuntu on the welcome screen.

The Ubuntu welcome screen.

5. When the live system boots up, connect to the internet.

6. Open the terminal and type the following command to add the repository for the Boot Repair tool.

sudo add-apt-repository ppa:yannubuntu/boot-repair
Adding the repository for the Boot Repair tool.

Press Enter and wait for the repository to be added.

7. Update the repositories.

sudo apt update

8. Install the Boot Repair tool.

sudo apt install boot-repair

9. Start the Boot Repair tool via the terminal.

boot-repair

10. Select Recommended repair.

Selecting Recommended repair on the Boot Repair main screen.

Wait for the tool to finish repairing the bootloader.

Note: The Boot Repair tool is available as a live image, so you can boot it from an external drive without using another live OS.

Updating GRUB config file

When the system successfully boots up, make sure the GRUB configuration is up to date.

Run this command:

update-grub
Updating GRUB in the Linux terminal.

Reinstalling GRUB

Follow the steps below to reinstall GRUB on your Linux system.

1. Mount the partition containing the OS installation. The example mounts the /dev/sda1 partition to the /mnt directory.

sudo mount /dev/sda1 /mnt

2. Bind the /dev, /dev/pts, /proc, and /sys directories to the corresponding directories in the /mnt folder.

sudo mount --bind /dev /mnt/dev &&
sudo mount --bind /dev/pts /mnt/dev/pts &&
sudo mount --bind /proc /mnt/proc &&
sudo mount --bind /sys /mnt/sys

3. Install GRUB.

sudo grub-install -root-directory=/mnt/ /dev/sda
Reinstalling GRUB in the Linux terminal.

4. Unmount the directories when the installation completes successfully.

sudo umount /mnt/sys &&
sudo umount /mnt/proc &&
sudo umount /mnt/dev/pts &&
sudo umount /mnt/dev &&
sudo umount /mnt

Conclusion

After reading this article, you should be able to fix your Linux boot failure using GRUB Rescue or Boot Repair utilities. For another way to fix your boot-related issues, read How to Use fsck Command.

grub rescue – что делать?

Время прочтения: 4 мин.

34 942

Содержание

    В случае возникновения проблем с загрузчиком появляется надпись grub rescue. Чаще всего проблема появляется, когда на компьютере установлено сразу две операционные системы: Linux и Windows. Обычно установка производится в такой последовательности.

    Сначала на жёсткий диск устанавливается Windows после чего на отдельный раздел производится установка Linux. При такой схеме в загрузочную область диска добавится загрузчик grub2 что позволяет выбирать в какую из систем производить запуск.

    Но бывает так, что в таком состоянии компьютер работает длительное время. У Windows как известно разрастается реестр, и система начинает работать медленно. Тут вы приняли решение переустановить Винду, а заодно затёрли загрузчик Linux. Загрузочная область оказывается повреждена и при старте системы появляется сообщение на чёрном экране: grub rescue unknown filesystem.

    grub rescue – что делать?

    Ещё вы могли что-нибудь нахимичить с файлом конфигурации grub.cfg в директории /boot/grub/. Его вообще не рекомендуется править редакторами поскольку в будущем он всё равно окажется перезаписан автоматически. Вместо этого сконфигурируйте файл /etc/default/grub и выполните команду: sudo update-grub

    Итак, мы находимся консоли загрузчика. Она имеет небольшой командный интерпретатор наподобие bash. Список всех доступных команд можно получить, набрав:

    help
    grub rescue – что делать?

    Введите команду для просмотра существующих разделов:

    ls
    grub rescue – что делать?

    В данном примере всего один раздел msdos1 на жёстком диске hd0.

    Убедимся, что это нужный раздел. Для этого выводим список файлов загрузчика:

    ls (hd0,msdos1)/boot/grub/

    Находим файл grub.cfg значит всё в порядке, продолжаем. Если каталог не обнаружен, то перебираем остальные разделы дисков пока не найдём.

    grub rescue – что делать?

    Следующая команда создаёт префикс для каталога загрузчика:

    set prefix=(hd0, msdos1)/boot/grub

    Установим раздел в качестве корневого:

    set root=(hd0, msdos1)/boot/grub

    Затем необходимо подключить ещё пару модулей и стартовать загрузку системы:

    insmod ext2
    insmod normal
    normal
    grub rescue – что делать?

    После успешной загрузки в Linux не забудьте переустановить загрузчик командой:

    sudo grub-install /dev/sd_

    (вместо «_» введите букву загрузочного жёсткого диска).

    Далее выполните команду обновления конфигурации файла grub.cfg:

    sudo update-grub

    Обычно grub2 автоматически определяет установленные системы, в том числе Windows, и добавляет их в список загрузки.

    Восстановление ubuntu с флешки

    Если все проделанные выше действия не помогли, то придётся раздобыть загрузочную флешку.

    Лучше подготовить USB или CD носитель с Ubuntu той же версии и разрядности что и восстанавливаемая система. Я покажу на примере системы Ubuntu 18.04 LTS x64. Загрузитесь в Live режиме и откройте терминал комбинацией Ctrl+Alt+T.

    Для удобства сразу активируйте права суперпользователя root. Знак минус в конце команды означает перемещение в домашний каталог:

    sudo su -
    grub rescue – что делать?

    Теперь нужно посмотреть список дисков и разделов программой fdisk:

    fdisk -l
    grub rescue – что делать?

    Обнаруживаем раздел с установленной системой Linux. В этом примере раздел /dev/sda1 единственный, он же корневой и загрузочный.

    ВНИМАНИЕ

    Выбирайте раздел аккуратно, буква диска может отличаться от моих примеров. Не потеряйте свои данные!

    Смонтируем его в каталог /mnt/:

    mount /dev/sda1 /mnt

    Убедитесь, что каталог /boot/ находится на этом же разделе диска выполнив команду:

    ls -l /mnt/boot/

    В случае отсутствия каталога, монтируйте его отдельно. Для этого нужно найти раздел в результате вывода утилиты fdisk (на скриншоте выше) и смонтировать командой:

    mount /dev/sdaX /mnt/boot

    X = номер вашего раздела с файлами каталога /boot/.

    Сейчас необходимо произвести логин в ту систему, которую будем чинить. Но перед этим смонтируем из Live системы несколько служебных разделов:

    mount --bind /dev /mnt/dev && mount --bind /proc /mnt/proc && mount --bind /sys /mnt/sys

    Двойной амперсанд && между командами означает проверку выполнения предыдущей команды. Выполнение последующей команды происходит только при условии, что предыдущая завершена успешно.

    Переходим в окружение chroot, то есть заходим под пользователем root в систему, установленную на жёстком диске:

    chroot /mnt

    Всё, мы в системе. Можно устанавливать загрузчик и обновлять его конфигурацию. Будьте внимательны, используется именно корневой раздел диска /dev/sda без цифры:

    grub-install /dev/sda && update-grub
    grub rescue – что делать?

    Посмотрите, чтобы не было ошибок в результате выполнения команд. Далее набираем один раз exit, или комбинацию Ctrl+D и выходим в консоль Live системы.

    На всякий случай размонтируем корректно разделы и перезагружаемся:

    umount –R /mnt; reboot

    Процедура восстановления загрузчика grub2 на этом завершена.

    Применение статьи на практике: https://onstartup.ru/forum/po-motivam-grub-rescue/

    Видео

    Grub — это универсальный загрузчик, который используется для загрузки операционной системы Linux и других ОС, в случае, если на компьютере установлен Linux. Но когда вы выполняете какие-либо действия с разделами на диске, например, восстанавливаете их с помощью Clonezilla, изменяете размер или что-то другое, что Grub может быть поврежден.

    Часто такие повреждения приводят к ошибке grub rescue unknown filesystem. Тогда перед вами не появляется меню, а только сообщение про ошибку и консоль восстановления для ввода команд. В этой небольшой статье мы рассмотрим как исправить эту ошибку.

    Ошибка grub rescue unknown filesystem может возникать по разным причинам вот самые распространенные причины:

    • Вы восстанавливали диск из Clonezilla и были изменены метрики раздела /boot;
    • Раздел /boot был отформатирован и больше не существует;

    Дело в том, что Grub устанавливается в два места. Первое — место в таблице разделов MBR. Там очень мало места, около 512 байт, а следовательно, весь загрузчик туда поместиться не может. Поэтому Grub имеет модульную структуру и все основные модули, конфигурационные файлы и ресурсы располагаются на обычном разделе, который монтируется после загрузки в /boot. Причем программа в MBR помнит где находится раздел /boot, но если с этим разделом что-то произойдет и программа не сможет загрузить привычные модули, то выдаст ошибку uncnown filesystem. Если раздела больше нет, то вам останется только брать LiveCD диск и переустанавливать загрузчик, если же раздел просто немного изменен, то еще можно все исправить.

    Как исправить Grub unknown error

    У вас есть простейший терминал с самой простой командной оболочкой. Чтобы знать какие команды можно там вводить наберите:

    help

    Дальше нам нужно посмотреть список доступных разделов, для этого используется команда ls, как в bash:

    ls

    Без модулей grub поддерживает только ту файловую систему, которая была на /boot. Вы можете попытаться просмотреть содержимое каждого раздела чтобы определить где находятся файлы модулей. Например:

    ls (hd0,1)/

    Если вы увидели папку boot, значит это наш раздел. Дальше устанавливаем этот раздел значением переменной root с помощью команды set:

    set root=(hd0,1)
    set prefix=(hd0,1)/boot/grub

    Загружаем и запускаем модуль normal, который должен загрузить все, что нам необходимо:

    insmod normal
    normal

    Если раздел /boot не был поврежден, то загрузчик нормально определит все файлы, а потом запустит привычное для вас меню. Конечно, после того, как система загрузится, вам будет необходимо восстановить загрузчик Grub чтобы не вводить эти команды при каждой загрузке системы.

    Выводы

    В этой статье мы рассмотрели почему возникает ошибка error unknown filesystem grub rescue и что делать grub rescue, когда вы видите это сообщение. Да, во многих случаях у вас уже не получится загрузить систему без LiveCD диска. Но иногда все можно спасти. Надеюсь, эта информация была полезной для вас.

    Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

    Creative Commons License

    Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

    Об авторе

    Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

    Понравилась статья? Поделить с друзьями:

    Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Ошибка при загрузке fldrclnr dll
  • Ошибка при загрузке firefox
  • Ошибка при загрузке error 0000e9
  • Ошибка при загрузке epic games

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии