How to Use Grub Rescue to Fix Linux Boot Failure

How to Use Grub Rescue to Fix Linux Boot Failure Хостинг

Updates

December 2009 update:

A few questions asked by my readers.

Do I need to do something if I am using an Ext3 filesystem? Can GRUB boot partitions be formatted to Ext4?

Answer:
May be. If your distribution supports Ext4, then yes, if it does not, then no, because it will not be able to read anything from partitions formatted in Ext4. The easiest way to overcome file system compatibility limitations is to use a separate Ext3-formatted partition under /boot. All modern Linux distributions will support this method.

I have two drives. Ubuntu Karmic is on the second disk. What should I use in the GRUB core.img file or can I use the normal sequential boot method ( chainload
)?

Answer:
If your bootloader is installed on the root of the second drive, then you can use the traditional sequential boot method ( chainload
). However, if you are using a single bootloader, then you should use the core.img file.

Why is the 40_custom script different from your custom scripts?

Answer:
The 40_custom script is already configured to be used when building the GRUB configuration file, according to the contents of the other scripts. However, you can write user scripts at any time. Required line in this script exec tail -n +3 $0
, but you don’t need to use it in your own scripts.

Will my scripts be updated if I update the kernel of another operating system installed on the same system?

Answer:
There will be no automatic update. You will need to rewrite the kernel references manually. One way to solve this problem is to create a symbolic link to the latest kernel and an initrd image (The starting root filesystem that is mounted first. initrd is part of the kernel, and is loaded as part of it at boot time. The kernel mounts the initrd in the first part of the boot process for later loading modules and the actual root filesystem.) using vmlinuz and generically named initrd. This is what openSUSE does, and allows you to keep your GRUB menu static. After updating the kernel, only symbolic links need to be changed. You do not need to change the GRUB configuration files.

I can’t set custom background in GRUB menu!

Answer:
Look at the section in the debian_theme script and set the use_bg option to true.

June 2010 update:

GRUB 2 current version is 1.98 and this is a stable release (Only tested developments get into the STABLE version. This is a guarantee that they will remain in the system further. As work progresses, when quite a lot of changes accumulate in STABLE and there is a guarantee of stability, STABLE is transferred to RELEASE That is, there are times when STABLE and RELEASE are completely identical.). There are a few small changes in functionality, but 99% of what is written above is still relevant.

GRUB 2 rescue CD (rescue disk)

If you are not using a Super Grub Disk (SGD) or live CD with a Linux distribution that supports GRUB 2, then you probably want to create your own GRUB 2 recovery CD (rescue CD). The advantage of this procedure is that the rescue CD will have its own GRUB menu.

This is done with the grub-mkrescue command, which is similar in syntax to Lucid Lynx
which is used in GRUB2-1.98-1ubuntu5 and Karmic
and earlier versions that used the beta version of the bootstrapper.

Now, let’s see how to do it:


$ grub-mkrescue --output=<name>.iso /boot/grub

You can use any name.

Ubuntu 9.10 and earlier:


$ grub-mkrescue --overlay=/boot/grub <name>.iso

After creating the ISO image, you write down
it on the CD. Then test it, preferably on another machine. Make GRUB boot from the CD, not the local drive. If you use filenames without a full path, the ISO image will be created in the current directory.

Set the target (test) host to boot from the CD, the rescue CD will load the GRUB command line. Make sure you actually booted from the CD and that it works as expected and contains your GRUB menu. To do this, run the following command:

$ configfile /grub.cfg

It will display your menu. If you are satisfied with the result, then keep this disk handy in case of emergencies. Remember to create a new ISO every time you update your GRUB menu.

You will use the rescue CD to boot the desired operating system and restore GRUB using the grub-install command as shown earlier. The Rescue CD will not work if you remove the operating system or partitions containing it.

How to make your own GRUB2RESCUE CD-ROM

There are also discussion threads available on the Ubuntu and wilderssecurity.com forums, but they mostly deal with the use of these same commands and their variations in various versions of Ubuntu.

Thanks to Ocky for this tip!

December 2010 update:

A few more changes. Here you will find their brief overview and additional information.

Conventions

Symbols have been changed again. For MS-DOS partitions, which represent the vast majority of partitions, GRUB 2 in Maverick (Ubuntu 10.10 Maverick Meerkat version) uses new designations. Instead of a universal designation hd(X,Y)
, now will be hd(X,msdosY)
, which can be a bit confusing. You should take this into account when creating complex multi-boot installations.

For more information, please see my review of Maverick
.

Additional Reading Information

Also welcome to official
Ubuntu forum in GRUB2 topic.

December 2011 update:

A few additional changes. The official version of GRUB is 1.99 and has several changes. First of all, important external changes have been made. In older versions of the kernel, the menu was presented as a single list, now it is displayed like a list of files in a separate directory, which makes it more readable. In addition, in Ubuntu, menus now display at a higher resolution and smaller font size. Now let’s look at some other changes.

Booting the Xen kernel in a multi-boot configuration under GRUB2

You saw this example in my introductory guide to Xen
. Peculiarities:

Please check if you are using sequential loading openSUSE
with GRUB 2, then you need to specifically create a configuration for the Xen kernel, which should not be automatically added using the OS probe script. Look at the difference between this configuration and standard boot blocks.

multiboot /boot/xen.gz
module /boot/vmlinuz-xen
module /boot/initrd-xen

Of course, it lists the full paths to your installations, devices, and so on. Here is a screenshot of the menu file found on my test machine:

Меню GRUB 2

Fedora 16 support

Fedora
16

also supports GRUB2. Some installations are slightly different from systems
based on Debian. Navigating Fedora will be a little more difficult for you.
after working in GRUB 2 on Ubuntu and systems from its family. GRUB2 support
Fedora is not well implemented, as it only recently supports
GRUB 2, and of course there are bugs in some features.

How to update the GRUB menu

To update, use the following command:

$ grub2-mkconfig -o /boot/grub2/grub.cfg

The command will create a grub.cfg file according to your scripts from /etc/grub.d.

Fedora - файл grub.d

Changing header script (default menu bar and timeout)

In Ubuntu, changing the default menu item and timeout is very easy. But in Fedora, this is not the case at all. File editing 00_header
is more complex. You must change the functionality of the script to get what you need.

The timeout is set by the make_timeout() function. This function accepts two input parameters, GRUB_TIMEOUT and GRUB_TIMEOUT_BUTTON, which are declared at the beginning of the 00_header script.

Заголовок файла

Variables will take on different values ​​depending on the parameters of the working environments and configurations. If it is difficult for you to keep track of the assignment of values, then you can simply assign them the required values.

Читайте также:  Как расширить файловую систему в Linux. Часть 1

функция make_timeout

In this case, modify the script as follows:

Be sure to back up first! And you don’t need to delete anything, just comment out the lines you don’t need. This method will allow you to return the previous state if required.

After editing the file, you must rebuild the grub.cfg file. After the file is updated, you can check if the timeout value from the configuration file is handled correctly.

Изменения времени ожидания

And now we are loading, notice the waiting time on the counter.

Загрузка

Additional Information

GRUB2 — FedoraProject.org

GRUB2 features — FedoraProject.org

If you think there is a need for a separate guide on how to use Fedora and GRUB2, then we can make it.

June 2012 update:

official released

GRUB version 2.00. G RUB 2 has become attractive in every respect. We’ll see
the main release version of GRUB 2 in various distributions by the end of this year.
For end users, the changes will be invisible. Just use this
guide and have a good time.

If you liked the article, share it with your friends:


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.
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.

Comparing GRUB legacy and GRUB 2

Now the good question is, which one will you use and which one won’t you?


GRUB legacy

This is an old version and is no longer being developed, but it works great and has proven itself well. Editing the GRUB menu is very simple and does not require high user experience, that is, you only need to create it according to the correct syntax and save it.


GRUB 2

GRUB 2 is a beta version of the software. The current version is 1.97, which could easily become official. This makes it a less successful candidate for production systems.

In addition, GRUB 2 is more difficult to work with for a number of reasons: a) it requires a strong command of the shell, which not everyone owns; b) changing the GRUB menu is much more difficult and requires three steps before it can be changed; c) changes are not automatically saved and must be «compiled» in the menu whenever changes are made, as is the case with the LILO bootloader.

Currently, GRUB 2 is supported by a small number of distributions, so it is unlikely to get support and find answers online (on the Internet, for example). Therefore, you have a chance to run into problems using GRUB 2 in a mixed environment.


Conclusion

In both GRUB tutorials, I showed that even complex situations can be resolved with relative ease. This can be done by sharing both GRUB legacy and GRUB 2 bootloaders, as detailed in my examples.
For now, GRUB legacy is probably better for you if you are not a very experienced user.

If you are running Ubuntu then you can leave GRUB 2 as the default bootloader. Just make sure you follow my instructions and you will have an easy and hassle-free download.

I highly recommend looking at the following articles, reviews, and howtos of the guide:


Official Information

GRUB 2 official site

GRUB 2 Manual

GRUB 2 Ubuntu Wiki documentation

GRUB 2 Command List


Other useful resources on GRUB 2

GRUB bootloader — complete guide
(my article) ( Russian translation
)

Herman’s GRUB pages
(great collection of howtos)

GRUB error messages

How to change GRUB 2 theme

GRUB 2 title tweaks
(additional material to help avoid the hassle of replacing menu items)

GRUB 2 on archlinux Wiki
(additional material)

How to install GRUB 2 on Ubuntu 9.04

Using the command shell

Since the MBR is too small to store all GRUB modules, only the menu and a few basic commands reside there. The majority of GRUB functionality remains in modules in /boot/grub/
, which are inserted as needed. In error conditions (e.g. if the partition layout changes) GRUB may fail to boot. When this happens, a command shell may appear.

GRUB offers multiple shells/prompts. If there is a problem reading the menu but the bootloader is able to find the disk, you will likely be dropped to the «normal» shell:

 grub>
  

If there is a more serious problem (e.g. G RUB cannot find required files), you may instead be dropped to the «rescue» shell:

 grub rescue>
  

The rescue shell is a restricted subset of the normal shell, offering much less functionality. If dumped to the rescue shell, first try inserting the «normal» module, then starting the «normal» shell:

 grub rescue> set prefix=(hdX,Y)/boot/grub
grub rescue > insmod (hdX,Y)/boot/grub/i386-pc/normal.mod
rescue:grub>normal
  

GRUB supports pager for reading commands that provide long output (like the help
command). This works only in normal shell mode and not in rescue mode. To enable pager, in GRUB command shell type:

 sh:grub> set pager=1
  

Using the command shell environment to boot operating systems

 grub>
  

The GRUB’s command shell environment can be used to boot operating systems.
A common scenario may be to boot Windows / Linux stored on a drive/partition via chainloading
.

Chainloading
means to load another boot-loader from the current one, ie, chain-loading.

The other bootloader may be embedded at the start of a partitioned disk (MBR), at the start of a partition or a partitionless disk (VBR), or as an EFI binary in the case of UEFI.


Chainloading a partition’s VBR

 set root=(hdX,Y)
chainloader +1
boot
  

For example to chainload Windows stored in the first partition of the first hard disk,

 set root=(hd0,1)
chainloader +1
boot
  

Similarly GRUB installed to a partition can be chainloaded.


Chainloading a disk’s MBR or a partitionless disk’s VBR

 set root=hdX
chainloader +1
boot
  


Chainloading Windows/Linux installed in UEFI mode

 insmod fat
set root=(hd0,gpt4)
chainloader(${root})/EFI/Microsoft/Boot/bootmgfw.efi
boot
  

insmod fat
is used for loading the FAT file system module for accessing the Windows bootloader on the EFI system partition.
(hd0,gpt4)
or /dev/sda4
is the EFI system partition in this example.
The entry in the chainloader
line specifies the path of the .efi
file to be chain-loaded.

See the examples in #Using the rescue console

Using the rescue console

See #Using the command shell
first. If unable to activate the standard shell, one possible solution is to boot using a live CD or some other rescue disk to correct configuration errors and reinstall GRUB. However, such a boot disk is not always available (nor necessary); the rescue console is surprisingly robust.

The available commands in GRUB rescue include insmod
, ls
, set
, and unset
. This example uses set
and insmod
. set
modifies variables and insmod
inserts new modules to add functionality.

  grub rescue> set prefix=(hd    X    
,    Y    
)/boot/grub
  

where X
is the physical drive number and Y
is the partition number.

Note:
With a separate boot partition, omit /boot
from the path (i.e. type set prefix=(hd X
, Y
)/grub
).

To expand console capabilities, insert the linux
module:

  grub rescue> insmod i386-pc/linux.mod
  
  grub rescue> insmod linux
  

This introduces the linux
and initrd
commands, which should be familiar.

An example, booting Arch Linux:

  set root=(hd0,5)
linux /boot/vmlinuz-linux root=/dev/sda5
initrd /boot/initramfs-linux.img
boot
  

With a separate boot partition (e.g. when using UEFI), again change the lines accordingly:

Note:
Since boot is a separate partition and not part of your root partition, you must address the boot partition manually, in the same way as for the prefix variable.

set root=(hd0,5)
linux (hd    X    
,    Y    
)/vmlinuz-linux root=/dev/sda6
initrd (hd    X    
,    Y    
)/initramfs-linux.img
boot

Note:
If you experienced error: premature end of file /YOUR_KERNEL_NAME
during execution of linux
command, you can try linux16
instead.

To reinstall GRUB and fix the problem completely, changing /dev/sda
if needed. See #Installation
for details.

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.

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.

Читайте также:  Vault.pictures не работает сегодня февраль 2022? Это только у меня проблемы с Vault.pictures или это сбой сайта?

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.

   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

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  
  

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?

Положительной чертой системного загрузчика GRUB 2 является возможность его переустановки при каждой необходимости. Таким образом, в том случае, если вы потеряете системный загрузчик GRUB 2, к примеру, после того, как ОС Windows заменит его на свой собственный загрузчик, вы сможете восстановить GRUB 2, выполнив несколько операций в live-окружении. Если предположить, что вы установили дистрибутив в раздел жесткого диска, представленный файлом устройства /dev/sda5
, вы можете переустановить системный загрузчик GRUB 2, в первую очередь создав директорию для монтирования корневой файловой системы дистрибутива с помощью команды:

  sudo mkdir -p /mnt/distro
  

После этого следует смонтировать файловую систему из этого раздела с помощью команды:

  mount /dev/sda5 /mnt/distro
  

После этого вы сможете переустановить системный загрузчик GRUB 2 с помощью команды:

  grub2-install --root-directory=/mnt/distro /dev/sda
  

Данная команда позволит перезаписать информацию в области основной загрузочной записи устройства /dev/sda
, содержащего файловую систему установленного дистрибутива Linux, а также такие файлы системного загрузчика GRUB 2, как grubenv
и device.map
.

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

Перед выполнением данной команды следует убедиться в том, что разделы с корневыми файловыми системами установленных дистрибутивов, которые не представлены в меню загрузки, смонтированы. Если дистрибутив, который вы желаете добавить в меню загрузки, работает с файловыми системы /root
и /home
, расположенными на отдельных разделах жесткого диска, перед исполнением команды grub2-mkconfig
следует смонтировать лишь файловую систему /root
.

Хотя системный загрузчик GRUB 2 и может определять большинство дистрибутивов, попытка добавления в меню системного загрузчика записи для дистрибутива Fedora при работе с дистрибутивом Ubuntu требует одного дополнительного шага. Если вы использовали стандартные настройки в процессе установки дистрибутива Fedora, силами его установщика будут созданы разделы LVM. В этом случае перед вызовом сценария os-prober
из комплекта поставки системного загрузчика GRUB 2 для добавления дистрибутива Fedora в меню загрузки вам в первую очередь придется установить драйвер lvm2
с помощью системы управления пакетами программного обеспечения дистрибутива, воспользовавшись аналогичной командой:

  sudo apt-get install lvm2
  

Пользовательские параметры меню загрузки

Системный загрузчик GRUB 2 использует большое количество конфигурационных переменных. This section describes some of these variables that you will most likely want to modify as you review the contents of the configuration file /etc/default/grub
. Variable GRUB_DEFAULT
allows you to specify the boot menu item to be selected by default. its values ​​can be numbers, such as the number 0, corresponding to the first menu item, as well as the string «saved», which automatically selects the menu item used during the last boot of the computer. Variable GRUB_TIMEOUT
allows you to set the duration of the waiting period before loading using the default menu item, and the variable GRUB_CMDLINE_LINUX
allows you to specify a list of options that will be passed to each of the Linux kernels when using the appropriate boot menu items.

In the event that the variable GRUB_DISABLE_RECOVERY
matters true
, boot menu items for system recovery will not be generated. These items allow you to boot distributions in single user mode, in which you can use any available command line interface tools to restore your system. Another useful variable is the variable GRUB_GFXMODE
, which allows you to set the screen resolution that will be set when the boot menu is displayed. This variable can be set to any description of the resolution supported by your graphics card.

GRUB 2 — development prospects

This is something you should be familiar with before trying out GRUB 2. When GRUB 2 becomes the de facto
bootloader for UNIX like operating systems? Currently GRUB legacy is fine
does well and will continue to do so for many years to come. Having received long-term support from companies,
like RedHat and Novell, in server distributions, GRUB legacy has remained a key player for the most
less than 5-10 years.

Deployment should be faster on desktop machines, but don’t expect miracles too much
fast. However, it won’t hurt to start learning about it. Take note, you will be faced with
some compatibility restrictions in the future, especially in many conservative
distributions that don’t adopt new technologies too quickly.

Now let’s move on to the real mechanisms.

Repair GRUB 2


Recovering from a Failed Boot

What if it happens that you damage GRUB 2? There must be a way to restore it and save the day? Everything is as usual, there are two ways: easy and difficult.

The Easy Way: Super Grub Disk

This is
is a powerful tool that works with GRUB 2, so don’t worry. Install it on a CD/DVD drive, boot from it and repair the damaged GRUB.

SGD

The Hard Way: Manual Fixing with a Live CD

You need a live CD like Ubuntu or Kubuntu that has GRUB 2 on board. Boot into a live session (temporary boot session of the operating system), mount the hard drive and install GRUB 2 into the MBR.

Here is the sequence of commands to run (assuming drive = /dev/sda). You need to mount a partition with your distribution installed (like Ubuntu) and containing the /boot directory. It can be a separate partition in the system, it depends on the options selected during system installation.

After mounting it, you need to run the command again grub-install
.


$ mount /dev/sda1 /mnt/
$ grub-install --root-directory=/mnt /dev/sda

If this does not work, then you will need to perform a long and complicated procedure, which is described in official
GRUB 2 Ubuntu Wiki documentation.

Use the fdisk command to find the root device before mounting it. As an example, let’s say /dev/sda1 is a /boot partition and /dev/sda2 is the root partition in your distribution.


$ sudo mount /dev/sda2 /mnt

If your /boot partition is on a separate partition, then you need to mount that as well.


$ sudo mount /dev/sda1 /mnt/boot

Next, unmount the devices using the —bind option. For more information on how the mount command works, please see the man page
.


$ sudo mount --bind /dev /mnt/dev

In fact, you now have a root system to mount. You can now change the location of root (/) to /mnt. This can be done using the chroot command.


$ sudo chroot /mnt

This means that a command executed in this terminal will access /mnt/. Now, reconfigure the GRUB package:


$ dpkg-reconfigure grub-pc

You must tell GRUB which device to use. You can make a selection using the spacebar. The devices shown will match the data in the device map file. If you have only one device, then there should be no confusion.

After that, you can exit the chroot command workbench. This is done by pressing the keyboard shortcut Ctrl + D. Then dismantle the devices. Dismount /dev first, and then everything else.


$ sudo umount /mnt/dev
$ sudo umount /mnt

Now reboot. G RUB 2 will be restored.

Custom Boot Menu Items

If you wish to add an item to your bootloader menu, you must add the appropriate stanza to the script named 40_custom
. You can use this boot menu item, for example, to boot a Linux distribution installed on a removable USB drive. Assuming the distribution partition on your USB removable drive is represented by a device file /dev/sdb1
, and the vmlinuz kernel image file and the initrd file are located in a subdirectory of the root directory ( /
), you will have to add the following stanza to the script file 40_custom
:

 menuentry "Linux on USB" {
set root=(hd1,1)
linux /vmlinuz root=/dev/sdb1 ro quiet splash
initrd/initrd.img
}
  

For better compatibility, you can use the UUID of the hard disk partition instead of the device and partition IDs as follows:

Читайте также:  Queue Burst

 set root=UUID=54f22dd7-eabe
  

Use the command sudo blkid
to get all UUIDs of hard drives attached to the system and their partitions. Similarly, you can add entries to the boot menu corresponding to any identified os-prober script, but distributions installed on the hard disk, of course, if you know on which disk each of the distributions is installed and in what path its kernel image files are located and an image of the initial file system.

If you liked the article, share it with your friends:


Quick Fix

If command execution grub2-install
does not lead to any positive changes and you cannot boot a Linux distribution, you will have to completely reinstall and reconfigure the bootloader. To accomplish this task, you can use a useful utility chroot
, which allows you to temporarily replace the root directory of the live environment with the root directory of the installed Linux system, which needs to be restored. You can use the Live CD of any Linux distribution that has the utility for this purpose chroot
. However, you should make sure that you are using the Live CD for the same CPU architecture as the distribution installed on the hard drive. Thus, if you wish to use the utility chroot
To recover a 64-bit installed system, you will need a Live CD for 64-bit systems.

After booting the Live environment, the first thing to check is the hard drive partitions of the machine. Use command fdisk -l
to display a list of all hard disk partitions and find out the number of the partition on which the GRUB 2 bootloader is installed, the operation of which you want to restore.

Let’s assume that you need to restore the bootloader of a distribution installed on a hard disk partition represented by a device file /dev/sda5
. Open a terminal emulator and mount this partition:

 sudo mount /dev/sda5 /mnt
  

Now you will have to mount the directories that must be available to the GRUB 2 bootloader in order to correctly detect other operating systems installed on the computer:

 $ 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
  

Now you can leave the live environment and go to the environment installed on the partition represented by the device file /dev/sda5
, distribution kit using the utility chroot
:

 $ sudo chroot /mnt /bin/bash
  

Everything is ready to install, check and update the GRUB 2 bootloader. As before, to reinstall the bootloader, use the command:

 sudo grub2-install /dev/sda
  

Due to the fact that the team grub2-install
does not affect the configuration file grub.cfg
, you will have to create it manually with the following command:

 sudo grub-mkconfig -o /boot/grub/grub.cfg
  

This sequence of commands should help fix bootloader problems. Your machine will now have a fresh copy of the GRUB 2 bootloader with a list of all operating systems and distributions installed on it. Before rebooting the computer, you must leave the chroot environment and unmount all used file systems in the following order:

 $exit
$ sudo umount /mnt/sys
$ sudo umount /mnt/proc
$ sudo umount /mnt/dev/pts
$ sudo umount /mnt/dev
$ sudo umount /mnt
  

After that, you can safely reboot the machine, which should again be under the control of the GRUB 2 bootloader, which is under your complete control!

Bootloader Recovery

Problems related to the GRUB 2 bootloader can bring the system into various states. The text displayed on the screen instead of the bootloader menu indicates the current state of the system. In the event that the system stops loading with an invitation grub>
, we can conclude that the GRUB 2 modules were loaded, but the configuration file could not be loaded grub.cfg
. This prompt is displayed in a fully functional bootloader shell, with which you can perform quite a lot of actions aimed at booting the system. If you see an invitation grub rescue>
, then it is easy to conclude that the system loader cannot detect its modules, as well as files with a description of the system boot parameters. However, if only the word ‘GRUB’ is displayed on your computer’s screen, you can draw the unfortunate conclusion that the boot loader could not even find the basic information that is usually stored in the master boot record.

You can fix these GRUB 2 problems using either the Live CD of any distribution or the GRUB 2 shell. If you are lucky, your bootloader will display a greeting grub>
, you will be able to use the full power of GRUB 2’s built-in shell to fix any errors.

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

The GRUB 2 bootloader allows you to use the command line mode, which can be activated by pressing the C key in the boot menu

The following commands will work as if prompted grub>
, and in the case of an invitation grub rescue>
. Team set pager=1
allows you to use the text scrolling mechanism to prevent it from automatically scrolling. You can also use the command ls
, which allows you to list all visible GRUB 2 hard disk partitions in a similar way:

 grub > ls
(hd0) (hd0,msdos5) (hd0,msdos6) (hd1,msdos1)
  

As you can see, this command allows you to display information about the layout of the hard disk partition table along with information about the partitions themselves.

Alternatively, you can use the command ls
in relation to each hard disk partition to find the partition with your root file system:

 grub > ls (hd0,5)/
lost+found/ var/ etc/ media/ bin/ initrd.gz
boot/ dev/ home/ selinux/ srv/ tmp/ vmlinuz
  

You can drop the partition type ID msdos
when writing the section name. Also, if you skip the slash at the end of the section name and run, for example, a command like ls (hd0,5)
you will get information about the partition, including information about the type of file system, its total size, and when it was last modified. If you have multiple root partitions created on your hard drive, you can read the contents of the file /etc/issue
by command cat
for the purpose of identifying the distribution in the same way: cat (hd0,5)/etc/issue
.

Assuming you have found the correct root file system on the partition (hd0,5)
, you must make sure that this file system contains a directory /boot/grub
and a Linux kernel image with the same name vmlinuz-3.13.0-24-generic
which you wish to download. Now, to boot the system, you just need to enter the following commands:

 grub> set root=(hd0,5)
grub> linux /boot/vmlinuz-3.13.0-24-generic root=/dev/sda5
grub> initrd /boot/initrd.img-3.13.0-24-generic
  

The first command tells the GRUB 2 bootloader information about the hard disk partition on which the distribution files are located for booting. The second command passes to it information about the location of the kernel image file within the specified hard disk partition, as well as information about the location of the root file system. The last line allows you to specify the location of the initial disk image file, the contents of which are stored in memory and used during the kernel boot process. You can use the auto-completion feature, which will save you a lot of time and effort when entering the kernel filenames and the initial disk image.

The entry of these strings must end with the entry after the next salutation grub>
teams boot
, which initiates the loading of the specified operating system using GRUB 2.

Your actions should be slightly different in case you encounter a greeting grub rescue>
. Since the system loader was unable to detect and load any of the required modules, you will have to load them manually:

 grub rescue > set root=(hd0,5)
grub rescue>insmod (hd0,5)/boot/grub/normal.mod
grub rescue > normal
grub > insmod linux
  

Obviously, as before, after the effective use of the command ls
to find the Linux root partition, you will have to mark this partition with the command set
. Next, you need to download the module normal
, after which it will return to standard mode with a greeting grub>
. The following command allows you to load the linux module in case it was not automatically loaded. After loading this module, you can proceed to transfer information about the location of the kernel image files and the initial disk image to the system loader and initiate the download of the distribution using the command boot
.

After successfully downloading the distribution, do not forget about the need to re-generate the GRUB 2 configuration file using the command:

 grub-mkconfig -o /boot/grub/grub.cfg
  

You will also have to install a copy of the bootloader into the MBR with the command:

 sudo grub2-install /dev/sda
  

Оцените статью
Хостинги