Время на прочтение5 мин
Количество просмотров151K
Привет, Хабр! Сегодня мы рассмотрим ситуацию, когда при двойной установке Linux & Windows загрузчик GRUB не стартует, давая возможность выбрать ОС, а автоматически загружается Windows. Немного теории:
GRUB (GRand Unified Bootloader) — программа-загрузчик операционных систем.
GRUB может загрузить любую совместимую с ней операционную систему. Среди них: Linux, FreeBSD, Solaris и многие другие. Кроме того, GRUB умеет по цепочке передавать управление другому загрузчику, что позволяет ему загружать Windows (через загрузчик NTLDR), MS-DOS, OS/2 и другие системы.
Значит с теорией мы немного разобрались (думаю этого будет достаточно), теперь же рассмотрим, какие бывают подводные камни, при установке Dual Boot Windows и Linux на одном компьютере.
Эксперимент производился на рабочей станции со следующими характеристиками:
Base Board Information
- Manufacturer: Acer
- Product Name: Aspire XC600
Memory Device
- Size: 4096 MB
- Type: DDR3
- Speed: 1333 MHz
- Manufacturer: Kingston
- Rank: 2
HDD
- product: ST500DM002-1BD14
- vendor: Seagate
- physical id: 0.0.0
- bus info: scsi@0:0.0.0
- logical name: /dev/sda
- size: 465GiB (500GB)
- capabilities: gpt-1.00 partitioned partitioned:gpt
Доказано, что проблем с установкой Debian 8.6 Jessie совместно с Windows 10 не обнаружено. Debian корректно прописывается в автозагрузке, GRUB запускается без ошибок и две ОС также работают нормально.
Но, как показала практика, не со всеми дистрибутивами такое происходит. При установке Ubuntu 16.04.1 вместо Debian на ту же рабочую станцию вылез первый подводный камень — GRUB не стартовал, и Windows 10 автоматом шла на загрузку.
Решение проблемы было найдено спустя недели три-четыре (тогда уже надоело считать, сколько времени убито на решение проблемы). Оно оказалось неожиданным, но в тоже время вся система заработала. Значит, если вы столкнулись с такой же проблемой, приведенная ниже инструкция может вам пригодится и сэкономить кучу времени.
Важно! До начала выполнения инструкции нужно подготовить LiveCD с дистрибутивом Linux Mint — все операции мы будем выполнять на нем (я выбрал этот дистрибутив из-за того, что на него спокойно можно установить Midnight Commander, что сложно сделать на LiveCD с Ubuntu, так мы получаем больше пространства для маневров). Также стоит заметить, что команда из под консоли update-grub вам не поможет, так как она рассчитана на случай, когда GRUB запускается, но не видит другие ОС кроме Линукса. Также рекомендую создавать резервные копии файлов/каталогов, над которыми вы осуществляете хоть малейшие изменения.
- Через терминал, с правами root смонтировать раздел с EFI в папку /mnt. В моем случае, это была команда mount /dev/sda2 /mnt.
- Введите команду sudo -s и подтвердите пароль (он пустой по умолчанию) для последующих операций (многие советуют не делать этого, а вводить sudo и команду для выполнения — я поддерживаю это мнение, но инструкция рассчитана на опытных пользователей системы Linux, которые понимаю, что делают все на свой страх и риск).
- Запустить Midnight Commander командой mc.
- Найти в файловой системе следующий каталог: EFI в папке /mnt.
- Переименовать каталог Microsoft во что-нибудь другое, например в Microsoft2.
- Создаем новый каталог с именем Microsoft.
- Заходим в только что созданный каталог Microsoft и частично создаем внутри его иерархию папок аналогичную старому Microsoft (тому, что переименовали). В моем случае он имел такую структуру папок: /boot/, затем куча папок и файл bootmgfw.efi рядом с ними. Нужно воссоздать структуру папок ровно до этого файла. Т.е. всё, что лежит рядом с ним — не нужно, а всё, что идет до него (т.е. родительские папки, соседние с ними тоже не нужны) воссоздаем в нашей новой папке Microsoft. В моем случае понадобилось создать только папку /boot, итоговый путь до нового каталога вышел таким: /EFI/Microsoft/boot. Можно просто скопировать все папки и файлы — проверено, это работает и можно не создавать все вручную.
- Находим в каталоге из шага 6 папку с именем нашего дистрибутива Линукса, в нашем случае это Ubuntu. Копируем (оригиналы файлов и папку ubuntu на всякий случай оставляем, не помешают) все файлы из данной в папки в итоговый каталог, созданный на предыдущем шаге: /EFI/Microsoft/boot.
- В получившейся файловой системе находим файл grubx.efi или grubx64.efi (будет только один из них: в зависимости от разрядности установленного Линукса). Переименовываем его в bootmgfw.efi.
- Находим файл /boot/grub/grub.cfg в файловой системе установленного Линукса. Открываем его для редактирования. Внутри него находим слово «Microsoft» в контексте строки, начинающейся с «chainloader» и заменяем это слово (должно быть только одно вхождение и именно в строке с «chainloader», так что не ошибетесь) на название каталога, в который мы переименовали Microsoft (т.е. на Microsoft2 в нашем примере). Сохраняем изменения в файле.
Также, в этом файле вы можете поменять названия в списке, который выводит GRUB. Например, вместо
openSUSE Leap 42.2 27.01
в части кода:
menuentry 'openSUSE Leap 42.2 27.01' --class opensuse --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-996b3ed5-150f-4de3-a40c-6d385e27d6de' {
load_video
set gfxpayload=keep
insmod gzio
insmod part_gpt
insmod ext2
set root='hd0,gpt6'
if [ x$feature_platform_search_hint = xy ]; then
search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt6 --hint-efi=hd0,gpt6 --hint-baremetal=ahci0,gpt6 996b3ed5-150f-4de3-a40c-6d385e27d6de
else
search --no-floppy --fs-uuid --set=root 996b3ed5-150f-4de3-a40c-6d385e27d6de
fi
echo 'Загружается Linux 4.4.36-8-default …'
linuxefi /boot/vmlinuz-4.4.36-8-default root=UUID=996b3ed5-150f-4de3-a40c-6d385e27d6de ro resume=/dev/sda7 splash=silent quiet showopts
echo 'Загружается начальный виртуальный диск …'
initrdefi /boot/initrd-4.4.36-8-default
}
Написать
openSUSE The best choice!:)
:
menuentry 'openSUSE The best choice!:)' --class opensuse --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-996b3ed5-150f-4de3-a40c-6d385e27d6de' {
load_video
set gfxpayload=keep
insmod gzio
insmod part_gpt
insmod ext2
set root='hd0,gpt6'
if [ x$feature_platform_search_hint = xy ]; then
search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt6 --hint-efi=hd0,gpt6 --hint-baremetal=ahci0,gpt6 996b3ed5-150f-4de3-a40c-6d385e27d6de
else
search --no-floppy --fs-uuid --set=root 996b3ed5-150f-4de3-a40c-6d385e27d6de
fi
echo 'Загружается Linux 4.4.36-8-default …'
linuxefi /boot/vmlinuz-4.4.36-8-default root=UUID=996b3ed5-150f-4de3-a40c-6d385e27d6de ro resume=/dev/sda7 splash=silent quiet showopts
echo 'Загружается начальный виртуальный диск …'
initrdefi /boot/initrd-4.4.36-8-default
}
Хоть мелочь, а приятно! Остальное в коде советую не трогать.
Если трудно разобраться с управлением Midnight Commander (в этом нет ничего страшного, у меня тоже в первый раз были проблемы с этой программой), все операции можно выполнить в файловом менеджере Nautilus (или в другом, не суть важно), но изначально запустив его под правами пользователя root.
После этого идем на перезагрузку и радуемся результату. Но, как оказывается, такая проблема есть и у дистрибутива OpenSUSE Leap 42.2. Как показала практика, если на компьютере установлен дистрибутив OpenSUSE с Windows 10, то приведенная выше инструкция не поможет. Точнее, она поможет, но только ее нужно дополнить. После выполнения основной части выполняем следующие шаги:
- После выполнения всех операций заходим в папку /EFI/opensuse/x86_64-efi/ (название итоговой папки x86_64-efi может быть другим в зависимости от архитектуры ПК)
- Копируем файл grub.efi (если у вас включена опция Secure Boot, там будет еще файл shim.efi, тогда советую скопировать их вместе)
- Заходим в папку /EFI/Boot и удаляем все файлы, которые там есть (при обновлении загрузчика они снова появятся, но в этом нет ничего страшного)
- Вставляем файл (или файлы), которые мы скопировали и спокойно идем на перезагрузку.
Вот и вся инструкция. Думаю, кому-то пригодится…
P.S. Если же у вас все хорошо, GRUB с OpenSUSE запускается, но не видит Windows, радуйтесь — проблема решается всего одной командной: grub2-mkconfig -o /boot/grub2/grub.cfg, а если у вас стоит Ubuntu, нужно выполнить просто update-grub.
Для тех же, кого заинтересовала данная тема, рекомендую прочитать статью: «Начальный загрузчик GRUB 2 — полное руководство».
You will learn everything you need to know about dual-booting Linux and Windows.
I assume you already have Windows installed on your computer and you only need to install Linux to dual boot. This post will guide you through the following key points of the dual boot installation:
- Essential BIOS settings for successful dual boot.
- How to shrink your Windows partition to get free space for Linux.
- How to install Linux, using Linux Mint as an example.
- How to set the boot order in your computer to see the menu where you can choose between Linux and Windows to boot.
- Finally, I will explain why I am not a fan of dual-booting and why I recommend using Windows in a virtual machine as I showed in this post.
*NOTE: Before you apply any actions from in this post, please back up all your important data.*
BIOS settings
Unfortunately, most of the computers have BIOS configured specifically for Windows, and likely you won’t be able to install Linux on it without changing some settings. BIOS interface may differ from one computer to another but the main settings are the same.
I will use the BIOS of my Acer Swift 1 laptop as an example here.
Get into BIOS
First, you need to get into BIOS, usually, you just need to press a specific key during the boot. In my Acer Swift 1, I press F2. Just google your computer model and bios key term, and you will find the key you need to press. Sometimes, you may also see it on the screen during the boot:
Set the BIOS password
Next, you may need to set a password in your BIOS because it won’t allow you to change any security settings without a password. This is the menu to set the password on my Acer Swift 1:
You should be able to find the same in your BIOS. It is also possible that you can proceed without setting a password.
Disable Secure booting and change the Boot order
Next, you need to go to the Boot menu and disable Secure booting and move your bootable USB flash drive to the first place in the boot order:
Check this description of the commands on the right or bottom of your BIOS interface, it explains how to navigate and change options in your BIOS.
I am not going to stop here on how to create a bootable USB drive. I have already explained how to create a bootable USB from the command line or using graphical programs.
Save BIOS settings
In the end, go to the exit menu and exit BIOS with saving the changes:
If you have done everything correctly, you should boot in your Live USB Linux system:
Get free space for Linux
Boot into Live Linux session
Boot from the Live Linux USB. I will use Linux Mint installer as an example here, if you use Ubuntu or any Ubuntu-based distro, the process will not differ at all. If your distro is not Ubuntu-based, you still need to do the same steps as you will see in this post but the installer may look slightly different.
To install Linux alongside Windows, you can actually select such an option in the installation wizard:
It will automatically find free space on your hard drive and install Linux there. However, if you want to have little more control over how much space you allocate to Windows and Linux, you can get free space and assign it for Linux manually.
Shrink the Windows partition with GParted
Most of the Linux distros have GParted included in a Live ISO. If it is not, install it from the Software Center. Then open GParted and select the hard drive with your Windows installed:
Your Windows hard drive will be partitioned similarly to the one you see above. Most likely it will have the EFI partition, and this means you need to install Linux in the EFI mode too.
To shrink the Windows partition to get free space for Linux, you need to select the largest partition, click on the Partition menu in GParted, and select resize.
All white space is free space. So, you can shrink this partition with your mouse, or by selecting its size precisely with the number. You can take a maximum of free space for Linux if you aim to use mainly Linux, but leave some free space for Windows too, because it may not be able to work without free space left.
Click resize. Read this warning to know the risk and click OK. You will see how your partitions will look like after you apply the resizing:
So far, no changes to your hard drive have been applied. It is only a plan of action. You still can cancel everything, if you have done a mistake somewhere. However, if you are happy with this partition table. Click apply. This action will be irreversible.
Resizing will take some time. Hopefully, it will finish successfully and you can proceed with the installation.
Install Linux
To install Linux, click on the Install icons on your desktop or in your menu.
The installation process is pretty standard.
I recommend to include the third party software in the installation:
Select Manual partitioning
As I mentioned before, you can select the option to Install Linux alongside Windows automatically, but I personally prefer the manual way. That’s why we shrank the Windows partition and released some free space for Linux. Manual way not only gives more control but it also helps to understand what happens to your system when you install two systems alongside each other. So, select Something else here:
Create Linux Partition
The new screen will show you the partitions of your hard drive. You need to select the free space we have created in the previous step. Then click on the add sign, to create a Linux partition in this free space:
You can keep all the options at default here but importantly you need to assign / as a mounting point to this partition.
You can also split this free space into two parts and assign one to the system / and one to /swap. But I believe it is much better to use a swap file instead. Ubuntu installer creates a swap file by default.
I already explained the difference between a swap file and swap partition previously.
Check the EFI partition
Next, you need to select the EFI partition, it is usually of several hundred megabytes in size. Make sure it is detected as EFI:
Boot loader installation
Boot loader installation doesn’t matter here because it will be UEFI installation, so the boot loader will be installed in the EFI partition. You can keep the default selection.
Format column
Finally, check that only the new Linux partition will be formatted in the Format column. Because if you have other partitions selected for formatting, be careful you will lose all the data stored in those partitions. If everything is fine, click Install.
Finalize the installation
While the system is installing, select your location, provide your user information, set the password, etc.:
And then just wait until the system is installed.
After the installation, reboot the system and do not forget to remove your installation USB when you are requested to do so:
Boot into the new system
You should see this GRUB menu after the reboot. Here you can select between Linux, which will boot by default in 10 sec, and Windows:
Boot options in BIOS
If it happened that after the reboot, you booted directly in your Windows and you did not see any Linux menu, do not get upset. Likely, you have done everything right and you just need to change the boot order in your BIOS. Like I had to do in my Acer Swift 1.
In the Main tab, find the Boot menu and enable it:
Change the Boot order
Then go to the Boot order and you should see an additional boot option there that appeared after you installed Linux. In my case, it is still called Windows Boot Manager without the code in brackets. This is actually my Linux boot file. I do not know why BIOS branded it as Windows. So, I make it a first boot option:
And save the BIOS changes. After the reboot, you should see the GRUB menu with the choice of boot options.
If you still boot into Windows by default, try to open the boot menu during the start of your system by pressing the F12 key (or whatever key is assigned to your BIOS Boot menu). It should bring this BIOS boot menu:
Where I can choose Ubuntu and my Linux Mint will boot. So, the BIOS Boot menu helps to make sure that Linux works, you just need to check your boot order settings, maybe Linux is not the first option there. Try different orders until you get Linux booting the first.
Why I do not recommend dual-booting
There are three main reasons I stopped dual-booting and this is also why I do not recommend dual boot.
-
If you use Windows in dual boot, it is possible that some updates of Windows may break your Linux installation. Theoretically, it should not happen, but it happens. Maybe Windows changes the Linux bootloader in the UEFI partition. I do not know.
-
If you dual boot, you will never switch to Linux. If you are used to Windows, you will tend to boot into Windows more often and you won’t like to reboot to get to Linux. So, you will not use Linux much and thus will never switch to Linux completely.
-
On the other hand, if you prefer Linux, Windows will just take too much space on your hard drive that is never used. So, this is not good either.
I recommend using Windows in a Virtual machine such as VirtualBox. This way your Windows can be accessed from within Linux. Windows will be less powerful than if it was installed in dual boot, but you still can do most of the things you would normally do. A virtual machine also isolates your Windows file system and this provides better protection against viruses. You can read my post on how to install Windows 10 in VirtualBox and maybe you will like that option more than dual-booting.
Here are some scenarios you could relate to:
You dual booted Ubuntu Linux with Windows but when you reboot, you do not see the Grub screen that allows you to choose between Windows and Linux. Instead, it boot straight into Windows.
Or perhaps you had a working dual boot system but you updated Windows and now your system boots straight into Windows. The usual grub menu is nowhere on the scene. It just kept booting into Windows 10 at each startup.
I have faced both scenarios in my long journey with Linux and computers. I have also seen people panicking over it. Some users even think that their Linux partition was deleted and they lost their data. That’s not the case, I assure you.
No need to panic here. Just calm down, take a deep breath and go into boot settings. The problem starts there and ends there.
If you too are unable to boot into Grub and you’re just rebooting Windows 10 repeatedly, here are a few steps you can take to troubleshoot and fix the issue.
📋
Read all the text carefully otherwise you may miss something important. Also, the boot settings look different for different systems. The screenshots may look different.
Method 1: Move Grub up the order
One of the reasons why a dual boot system boots automatically into Windows is because the Windows boot manager has priority in the boot order.
You need to access the boot settings. Restart your system. When the computer is booting up and shows the manufacturer’s logo, quickly press F10/F12 or F2 keys to access the boot menu or settings.
The keys differ from manufacturer to manufacturer. You can cycle through themes one by one, quickly to avoid multiple booting.
Some systems will show a boot menu with possible options under the boot tab. If you are lucky, it will show the boot options like this:
You have to change the boot order if you can see both Windows and Linux boot options and Windows boot is above Linux.
You should see the option to access boot settings. Access it. Here, identify the Linux boot option. Select it and move it up the order using the F5 key. After that press F10 to save and exit. Helpful keyboard shortcuts are always displayed in the boot menu.
If you are lucky, this should fix the issue for you. If a few weeks or months down the line, the problem comes again after a Windows update, you can use this same method here.
But if there is no Ubuntu/Linux option in the boot menu?
Method 2: Add Linux boot entry in the boot settings
Many people encounter another common issue: the absence of Linux grub entry from the boot options. This means that there is only Windows, no Linux option in the boot settings.
If it is the same case with you, go to BIOS settings. Under the boot tab, look for the Add Boot Option.
It should give you the option to add an EFI file.
I used this while installing Debian Linux. This is why you’ll see Debian in the screenshots here. It should show the name of your Linux distribution like Ubuntu.
There is an EFI directory with efi files related to the operating systems on your computer i.e. Windows and Linux.
It should show a folder with your Linux distribution’s name along with some other folders. Select the Linux folder.
In this folder, you’ll find files like grubx64.efi, shimx64.efi. Select shimx64.efi.
You may give this file an appropriate name that is easily identifiable. The final screen may look like this.
Now, you should have this boot option. Since I named it Debian, it shows two Debian boot options (one of them coming from the efi file I guess). Press F10 to save and exit the BIOS settings.
When your system boots now, you should see the grub screen now.
What you did here can also be done from the Windows command line. Only try it when your settings are not taken into account.
Method 3: Set Linux boot for EFI from Windows (last resort)
🚧
Playing with your boot settings can leave your system messed up. I advise having a recovery disk or Windows installation disk with you to reverse boot settings. Keeping the Linux live USB can also help in many situations.
Step 1
In Windows, go to the menu.
Step 2
Search for Command Prompt, right click on it to run it as administrator.
Step 3
This is strictly for Ubuntu. Other distributions might have some other folder name.
In here, copy and paste the command below:
bcdedit /set {bootmgr} path \EFI\ubuntu\grubx64.efi
You don’t need to enter a password or anything like that. The command should run just fine given that your account has admin rights.
Step 4
Restart and the familiar Grub screen will welcome you. I hope this quick tutorial helped you fix the Grub issue.
No success? Revert the changes
If the above method didn’t change anything, reverse the changes. If you are not able to boot do not panic.
Access the boot settings when your system is booting. Here, go to the boot options and move Windows boot up the order. Save and exit.
Now when you boot into Windows. you can reverse what you did using the command below with the command prompt opened as admin:
bcdedit /deletevalue {bootmgr} path \EFI\ubuntu\grubx64.efi
Next, use the below command to set the boot back to Windows.
bcdedit /set {bootmgr} path \EFI\Microsoft\Boot\bootmgfw.efi
Did it work?
If you still cannot boot into the Windows installation, insert the Windows installation disk and there you’ll have access to the command prompt. If you see a “no boot found” error, you can try this or this solution.
Fix “No Bootable Device Found” Error After Installing Ubuntu Linux
Did you install Linux afresh or perhaps dual booted it? And now your system shows ‘no bootable device’ error while booting? Here’s what you could do to fix the issue. Usually, I dual boot Ubuntu and Windows but this time I decided to go for a clean Ubuntu installation
It’s FOSSAbhishek Prakash
Frustrating, isn’t it? It seemed like there was no way to access Linux at all. It seemed like the Linux partition disappeared but no – the Linux install on the other partition was safe and sound. It was just the UEFI settings that were different in the boot manager. I verified everything by accessing the UEFI firmware settings in Windows 10.
I hope the suggestions here helped you to get the Grub boot menu back and you can now use it to enjoy both Windows and Linux.
Как вернуть меню выбора ОС после установки Windows рядом с Linux? Рассказываем о двух способах восстановления загрузчика GRUB — для новичков (с утилитой boot-repair) и для продвинутых пользователей (с помощью chroot).
Поставили Windows рядом с Ubuntu, и теперь можете запустить только ОС от Майкрософт? Рассказываем, как восстановить загрузчик GRUB после установки Windows 10 или 11 — вам хватит 20 минут, даже если вы новичок в администрировании VPS.
Аренда VPS/VDS виртуального сервера от AdminVPS — это прозрачная и честная услуга с доступной ценой
Представьте: вы установили Ubuntu, настроили систему, а потом решили поставить Windows рядом. Но после перезагрузки вместо привычного меню GRUB (grand unified bootloader) вы увидите только загрузчик Windows. Это происходит потому, что Windows не дружит с альтернативными загрузчиками: при установке она перезаписывает главную загрузочную запись (MBR) или заменяет файлы в разделе EFI. И если GRUB, стандартный загрузчик для Linux, может работать с несколькими ОС, то загрузчики NTLDR (Windows 11) и Bootmgr (Windows 10) не умеют. Когда вы ставите Windows после Ubuntu, они просто «не видят» ОС, установленную первой.
Что нужно знать перед восстановлением GRUB
Прежде всего разберёмся с базовыми понятиями — это поможет избежать ошибок и сэкономит время.
UEFI или BIOS
Современные компьютеры используют два типа firmware (микропрограммы для управления железом):
- BIOS — это устаревший стандарт, загрузчик записывается в первый сектор диска (mbr);
- UEFI — современная замена BIOS, работает с разделом EFI (fat32), где хранятся файлы загрузчиков в формате .efi.
Чтобы проверить, какой режим на вашем компьютере, зайдите в bios/uefi (нажмите клавишу del, f2 или f12 при запуске). Если в настройках есть пункты Secure Boot, UEFI Mode — значит, у вас используется UEFI.
Или выполните в Linux:
ls /sys/firmware/efi
Если директория существует — система загрузилась через UEFI.
Live USB с Linux
Чтобы восстановить GRUB, понадобится загрузочная флешка с любым дистрибутивом (Ubuntu, Fedora, Mint).
Как создать Live USB:
- Скачайте iso-образ с официального сайта ОС.
- Создайте Live USB с помощью специальных программ:
- Rufus (на Windows) — выберите «GPT для UEFI» или «MBR для BIOS» в зависимости от прошивки вашего компьютера;
- BalenaEtcher (на Linux/Mac).
- Проверьте целостность образа после записи (в некоторых программах есть опция «verify»).
Как восстановить GRUB из-под Windows: два способа
Восстановление через boot-repair (для новичков)
Если вы не хотите работать в терминале, воспользуйтесь утилитой boot-repair. Она автоматизирует 90 % работы.
Шаг 1. Загрузка с Live USB
- Вставьте флешку, перезагрузите компьютер.
- Нажмите клавишу выбора загрузочного устройства (обычно f12, ESC или f8).
- Выберите флешку в меню.
Если у вас UEFI, загружайтесь в режиме UEFI, а не в Legacy! Иначе раздел EFI не будет обнаружен.
Шаг 2. Установка boot-repair
- Откройте терминал в Live-системе.
- Добавьте репозиторий и установите утилиту (далее все команды выполняются в режиме суперпользователя):
add-apt-repository universe # добавляйте репозиторий в Ubuntu до версии 22.04
apt update
apt install -y boot-repair
Шаг 3. Запуск и настройка
- Запустите boot-repair:
boot-repair
- Выберите «recommended repair».
- Следуйте инструкциям на экране: утилита сама определит установленные ОС, восстановит GRUB и обновит конфигурацию.
Если возникли ошибки:
- проверьте подключение к Интернету (boot-repair иногда скачивает дополнительные пакеты);
- убедитесь, что live-система загружена в правильном режиме (uefi/bios).
Ручное восстановление через chroot (для продвинутых пользователей)
Если первый метод не сработал или вы хотите понять процесс изнутри, восстановите GRUB вручную.
Шаг 1. Определение разделов
- Загрузитесь с Live USB.
- Откройте терминал и узнайте список дисков:
fdisk -l
или
lsblk -f
Команда lsblk -f показывает типы файловых систем и точки монтирования.
- Пример вывода lsblk:
NAME FSTYPE LABEL UUID MOUNTPOINT
sda
├─sda1 ntfs Windows ABCD-1234
├─sda2 ext4 Ubuntu 5678-90AB
└─ sda3 vfat ESP CDEF-1234
Обратите внимание на:
- корневой раздел Linux (ext4, btrfs и т. д.) — нам нужен именно он;
- раздел EFI (vfat) — если система на UEFI;
- раздел подкачки (swap) — не нужен для восстановления.
Шаг 2. Монтирование разделов
- Создайте точку монтирования:
mkdir /mnt/Linux
- Примонтируйте корневой каталог с Ubuntu:
mount /dev/sda2 /mnt/Linux
Для UEFI примонтируйте каталог EFI:
mount /dev/sda3 /mnt/Linux/boot/efi
Если у вас отдельный раздел /boot, монтируйте его:
mount /dev/sdaX /mnt/Linux/boot
Шаг 3. Вход в chroot
Chroot (change root) — это команда, которая изменит видимый корневой каталог, чтобы вы вошли в систему из live-окружения.
- Привяжите системные директории:
mount --bind /dev /mnt/Linux/dev
mount --bind /proc /mnt/Linux/proc
mount --bind /sys /mnt/Linux/sys
- Войдите в среду chroot:
chroot /mnt/Linux
Шаг 4. Установка GRUB
- Если прошивка BIOS (MBR):
grub-install /dev/sda # здесь sda — диск, а не раздел
update-grub
- Если прошивка UEFI (GPT), убедитесь, что пакет grub-efi установлен:
apt install grub-efi-amd64
Перед grub-install нужно обновить загрузочный список в efibootmgr, иначе в некоторых UEFI-системах GRUB не будет загружаться:
efibootmgr -c -d /dev/sda -p 1 -L "GRUB" -l "\EFI\GRUB\grubx64.efi"
Здесь -d /dev/sda — диск, -p 1 — номер EFI-раздела (уточните их с помощью lsblk).
Установите GRUB в раздел EFI:
grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=GRUB
- Обновите конфигурацию:
update-grub
- После update-grub в выводе должны появиться строки «found Windows» или «found os probe entries».
Шаг 5. Выход и перезагрузка
- Выйдите из chroot:
sync # запись данных
exit
- Отмонтируйте разделы:
sudo umount -R /mnt/Linux
- Перезагрузите компьютер.
Возможные проблемы и их решение
Даже если вы всё сделали правильно, могут возникнуть проблемы.
GRUB не видит Windows
Причина: os-prober не активирован (утилита для автоматического обнаружения установленных ОС).
Решение. В /etc/default/grub раскомментируйте строку:
GRUB_DISABLE_OS_PROBER=false
Установите os-prober:
apt install os-prober
Обновите загрузчик (update-grub).
Ошибка «grub-install: error: cannot find efi directory»
Причина: неправильно указан путь к разделу EFI.
Решение. Проверьте, примонтирован ли раздел EFI в /boot/efi. Проверьте тип раздела: он должен быть vfat (FAT32).
Загрузчик установился, но система не загружается
Причина: неверный порядок загрузки в uefi/bios или повреждённые файлы GRUB. Также включённый Secure Boot может блокировать работу GRUB.
Решение. Зайдите в настройки UEFI/BIOS и выберите GRUB в качестве первого загрузочного устройства. Отключите Secure Boot в UEFI. Если это не помогло — переустановите GRUB через chroot.
Как избежать проблем в будущем
- Если планируете устанавливать две операционные системы, то сначала установите Windows, потом Linux.
- Создайте резервную копию EFI/MBR.
Для BIOS:
dd if=/dev/sda of=backup.mbr bs=512 count=1
Для UEFI — просто скопируйте содержимое раздела EFI в место для хранения.
- Создайте отдельный раздел EFI для Linux. Это минимизирует конфликты с Windows.
Заключение
Восстановить загрузчик GRUB после установки Windows — задача, которая кажется сложной только на первый взгляд. Даже если вы новичок, boot-repair справится за пару кликов. Для тех, кто хочет глубже разобраться в процессе, подойдёт ручной способ через chroot.
Наши технические специалисты помогут вам определиться с конфигурацией и настроят ваш VPN-сервер под ключ, если это будет необходимо.
Читайте в блоге:
- Как поменять TTL для раздачи Интернета: настройка Default TTL и изменение значения на 64 или 65
- Что такое директория в Linux
- Как сменить владельца папки и изменить права доступа в Linux
Dual-booting any version of Microsoft’s Windows operating system with a Linux or BSD desktop or server distribution is a very common practice. For first time users of Linux, that is the easiest way to keep using Windows, while getting used to their choice of Linux distribution.
One of the most important decisions you have to make when dual-booting Windows and your favorite Linux distribution, is where to install the Linux boot loader. It could either go in the target hard drive’s Master Boot Record (MBR), or in the first sector of its own boot or root partition.
To make managing your dual-boot system less of a hassle, especially when both operating systems are installed on the same hard drive, the recommended location (for the Linux boot loader) is in the first sector of the Linux distribution’s boot or root partition. After that, you must then add an entry for the Linux distribution in the Windows boot menu.
The best graphical application that I have found to help you accomplish that task, is EasyBCD, a free application (free for personal use, that is) from NeoSmart Technologies. You may download it from here. The rest of this article shows how to use it to add an entry for any Linux distribution in the Windows boot menu. Note: This also applies to any of the BSDs, like PC-BSD.
After downloading it, install it as you would any other Windows application. It should start if installation is successful. The main window is shown below. To add the entry, click the Add New Entry tab.
Then click on the Linux/BSD tab. By default, GRUB (Legacy) should be preselected in the Type dropdown menu. If your distribution still uses that version of GRUB, then you just need to modify the Name field to reflect the distribution you are adding and select the partition where you installed GRUB from the Device dropdown menu.
However, if your distribution uses GRUB 2, as most Linux distributions do, select it from the Type dropdown menu, then modify the Name field to suite. That is all you need to do when using GRUB 2. If selecting GRUB 2 does not work for you, even when you know that GRUB 2 is the distribution’s boot loader, selecting GRUB (Legacy) also seems to work.
This is what the window should look like after selecting the right options. Click Add Entry.
You can see a preview of the entries in the boot menu in the Edit Boot Menu tab. Exit EasyBCD, restart the computer and try logging into the operating systems just to make sure that you can.
