Add windows 10 to grub2

Windows 10 will, for the most part, be added to grub boot menu by the os-prober automajically.

For my specific setup I wanted to completely hide grub menu and automatically boot windows unless a hotkey was pressed to boot Ubuntu. So in my specific case os-prober isn’t an option because the most important step in hiding the grub menu, which most answers I found neglect to mention, is to set the disable os-prober flag or the menu WILL be shown until os-prober completes.

It took considerably longer than I had anticipated to get right because there are so many partial answers out there but most are version dependant and can lead you astray. I spent a lot of time trying write my own grub menu entry trying use grub commands that didn’t exist like ntdlr. Another caveat is that the chainloader functions on my grub try to boot bios not efi and will not work.(Im sure I was doing something wrong?)

In the end the solution was actually simple as the scripts that make your /boot/grub/grub.cfg do most of the work for you in finding UUIDS for your boot partitions. So you can skip the fdisk and blkid steps most people mention.

So step 1 is to make sure /boot/grub/grub.cfg is current using update-grub to make .cfg file. In terminal

sudo update-grub

Step 2 is to add custom menu entries in /etc/grub.d/40_custom. Don’t waste time trying to write your own simply open /boot/grub/grub.cfg search «menuentry» and copy the automatically generated entries.

The first in the list will be ubuntu mine looks like

menuentry 'Ubuntu' --class ubuntu --class gnu-linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-9e66eed6-e672-49ff-a07c-afdc00809148' {
recordfail
load_video
gfxmode $linux_gfx_mode
insmod gzio
if [ x$grub_platform = xxen ]; then insmod xzio; insmod lzopio; fi
insmod part_gpt
insmod ext2
if [ x$feature_platform_search_hint = xy ]; then
  search --no-floppy --fs-uuid --set=root  9e66eed6-e672-49ff-a07c-afdc00809148
else
  search --no-floppy --fs-uuid --set=root 9e66eed6-e672-49ff-a07c-afdc00809148
fi
linux   /boot/vmlinuz-5.4.0-39-generic root=UUID=9e66eed6-e672-49ff-a07c-afdc00809148 ro  quiet splash $vt_handoff
initrd  /boot/initrd.img-5.4.0-39-generic

}

Windows will be similar. Copy both to /etc/grub.d/40_custom. The only change I made for Ubuntu is to add the —hotkey=key flag which will make grub boot the os associated with that hotkey.

menuentry 'Ubuntu2' --class ubuntu --class gnu-linux --class gnu --class os --hotkey=u $menuentry_id_option 'gnulinux-simple-9e66eed6-e672-49ff-a07c-afdc00809148' {
recordfail
load_video
gfxmode $linux_gfx_mode
insmod gzio
if [ x$grub_platform = xxen ]; then insmod xzio; insmod lzopio; fi
insmod part_gpt
insmod ext2
if [ x$feature_platform_search_hint = xy ]; then
  search --no-floppy --fs-uuid --set=root  9e66eed6-e672-49ff-a07c-afdc00809148
else
  search --no-floppy --fs-uuid --set=root 9e66eed6-e672-49ff-a07c-afdc00809148
fi
linux   /boot/vmlinuz-5.4.0-39-generic root=UUID=9e66eed6-e672-49ff-a07c-afdc00809148 ro  quiet splash $vt_handoff
initrd  /boot/initrd.img-5.4.0-39-generic

}

I use —hotkey=u here to set Ubuntu boot hotkey to u.

Then I tweaked the Windows entry, replacing $menuentry_id_option withe the grub —id flag.

menuentry "Windows 10" --class windows --class os --id windows-custom {
insmod part_gpt
insmod fat
if [ x$feature_platform_search_hint = xy ]; then
  search --no-floppy --fs-uuid --set=root  0EAE-C882
else
  search --no-floppy --fs-uuid --set=root 0EAE-C882
fi
chainloader /EFI/Microsoft/Boot/bootmgfw.efi

}

I used —id windows-custom. Save chages to /etc/grub.d/40_custom.

Finally open /etc/default/grub and add

GRUB_DISABLE_OS_PROBER=true

change GRUB_DEFAULT=0 to GRUB_DEFAULT=windows-custom
and change GRUB_TIMEOUT=10 to your choice of timings I use 0.5 just to give myself a little extra time to hit u to boot Ubuntu after POST.

Hopefully this saves someone a bit of headache, cheers!

It looks like you’ve followed an old guide that expects Windows to use MBR partitioning.

The «invalid signature» error suggests Secure Boot is enabled. When Secure Boot is enabled, all bootloaders must be signed with a private key, and a matching public key must be included in the Secure Boot variables in the firmware NVRAM. GRUB is dutifully reading the first sector of the partition you’ve specified, but since it does not contain the appropriate Secure Boot signature, the firmware refuses to execute it.

Secure Boot requires native UEFI-style boot as a prerequisite. You may be able to disable Secure Boot on your system, but since GRUB already starts for you, there is probably no need to do that.

Your insmod part_gpt suggest you expect the disk to have a GPT-style partitioning which usually goes together with UEFI boot style, but on the other hand, set root=(hd0,msdos2) expects a MBR partition.

On my Debian system with GPT partitioning, the set root line reads: set root='hd0,gpt1'. If your system uses GPT partitioning, use the gptN partition identifiers instead of msdosN.

Also chainloader +1 tells GRUB to read the boot block from the first block of the partition; in UEFI native boot, there is no such thing. To boot Windows in UEFI mode, the set root line should point to the EFI System Partition that contains the Windows bootloader, and the chainloader line should be chainloader /EFI/Microsoft/Boot/bootmgfw.efi.

  1. I have installed Windows 10
  2. I have installed Linux Mint Silvia and I have chosen a device for boot loader installation — sda.
  3. There is not Windows 10 in grub menu when the system starts
  4. I have booted via Linux Mint live USB.
  5. I Do step by step https://howtoubuntu.org/how-to-repair-restore-reinstall-grub-2-with-a-ubuntu-live-cd
  6. But it still no Windows 10 in grub menu
  7. I have booted via live windows 10 USB.
  8. With restoration tools, I have chosen the command line
  9. I have fixed Mbr by console command bootrec /FixMbr
  10. Ok, windows 10 is loading by there is no Grub.
  11. I have repeated steps 4 and 5
  12. There is no result

Also, I have tried to change grub config with this answer
https://askubuntu.com/questions/661947/add-windows-10-to-grub-os-list#answer-977251 — But in this case, There is Windows 10 — but when I chose — I will recursively going to grub

And with this answer
https://askubuntu.com/questions/661947/add-windows-10-to-grub-os-list#answer-890562
I have an error message when chose Windows 10 — There is no bootmgr directory

Thanks @Kinnectus for help

Also, I have tried

sudo os-prober

And getting

/dev/sda1:FreeDOS:FreeDOS:chain
/dev/sda2:FreeDOS:FreeDOS1:chain

And then I have tried

sudo update-grub

And getting

Generating grub configuration file ...
Found linux image: /boot/vmlinuz-4.10.0-38-generic
Found initrd image: /boot/initrd.img-4.10.0-38-generic
Found memtest86+ image: /boot/memtest86+.elf
Found memtest86+ image: /boot/memtest86+.bin
Found FreeDOS on /dev/sda1
Found FreeDOS on /dev/sda2
done

Unfortunately — there is not Windows 10 in grub menu

Also, I have fdisk output.

Device     Boot     Start       End   Sectors   Size Id Type
/dev/sda1            2048  16779263  16777216     8G  c W95 FAT32 (LBA)
/dev/sda2  *     16779264  33556479  16777216     8G  c W95 FAT32 (LBA)
/dev/sda3        33556480 770219115 736662636 351,3G  7 HPFS/NTFS/exFAT
/dev/sda4       770220030 976771071 206551042  98,5G  5 Extended
/dev/sda5       770220032 976771071 206551040  98,5G 83 Linux

Partition 4 does not start on physical sector boundary.

There is an issue.
Maybe the problem is with this issue?

Please, help me, I am stucking with this a whole day.
I completely have no idea, what am I doing wrong.

Grub2 — это загрузчик операционных систем, который позволяет выбирать, какую ОС запустить при старте компьютера. Он является стандартным загрузчиком для большинства дистрибутивов Linux и предоставляет возможность выбора ОС и редактирования конфигурации загрузчика. Однако по умолчанию grub2 не содержит информацию о Windows, и поэтому необходимо добавить эту ОС в меню grub2 вручную.

Чтобы добавить Windows в grub2, нужно выполнить несколько простых шагов. Первым делом нужно открыть файл конфигурации grub2. Он обычно расположен в директории /etc/grub.d/ и называется 40_custom. Для редактирования файла конфигурации понадобится права суперпользователя, поэтому его открывают и редактируют командой sudo gedit /etc/grub.d/40_custom.

После открытия файла конфигурации необходимо добавить блок следующего вида:

menuentry «Windows» {

set root=(hd1,1)

chainloader +1

}

Вам может потребоваться изменить параметр set root=(hd1,1) в зависимости от того, на каком разделе находится ваша ОС Windows. По умолчанию, hd1 означает второй физический диск, а 1 — первый раздел на этом диске. Если ваша ОС находится на другом диске или разделе, нужно изменить соответствующие значения.

После того, как вы добавили блок для Windows в файл конфигурации, нужно сохранить и закрыть его. Далее выполните команду sudo update-grub. Она обновит меню grub2 и добавит Windows в список доступных ОС при загрузке компьютера. Теперь вы можете выбрать Windows при старте и запустить его без проблем.

Содержание

  1. Шаг 1: Подготовка к добавлению Windows в grub2
  2. Шаг 2: Установка os-prober для обнаружения Windows
  3. Шаг 3: Редактирование файла конфигурации grub2
  4. Шаг 4: Перезапуск grub2 для применения изменений
  5. Шаг 5: Проверка добавления Windows в grub2

Шаг 1: Подготовка к добавлению Windows в grub2

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

1. Вставьте установочный диск или USB-накопитель в компьютер и перезагрузите систему.

2. Загрузитесь с установочного носителя и выберите опцию «Установить Linux» или подобную.

3. Далее, следуйте инструкциям установщика Linux и укажите параметры разделов для установки. Убедитесь, что вы выбрали то же самое хранилище, где уже установлена ваша текущая версия Linux. Если на вашем компьютере уже установлен только Windows, вы можете создать новый раздел для Linux.

4. Укажите раздел для загрузчика. В большинстве случаев, выбор будет автоматическим и установщик выберет раздел с Linux, однако, убедитесь, что загрузчик будет установлен на тот же раздел, где уже находится ваша текущая версия Linux.

5. После завершения установки выберите опцию перезагрузки системы. Теперь ваш компьютер должен загрузиться с установленной версией Linux.

Шаг 2: Установка os-prober для обнаружения Windows

  1. Открой терминал. Это можно сделать нажатием `Ctrl + Alt + T`.
  2. Введи команду `sudo apt-get install os-prober` в терминале.
  3. Нажми Enter и введи пароль администратора системы.
  4. Дождись завершения установки os-prober.

После завершения установки os-prober, теперь grub2 будет автоматически обнаруживать Windows при создании меню загрузки. Переходи к следующему шагу, чтобы настроить grub2 для добавления Windows в меню загрузки.

Шаг 3: Редактирование файла конфигурации grub2

1. Откройте терминал и выполните следующую команду, чтобы отредактировать файл конфигурации grub2:

sudo nano /etc/default/grub

2. Найдите строку GRUB_DEFAULT=0 и измените значение на GRUB_DEFAULT=saved. Это позволит сохранить последний выбраный вариант загрузки.

3. Добавьте следующие строки после строки с опцией GRUB_DEFAULT=saved:

GRUB_SAVEDEFAULT=true

GRUB_TIMEOUT_STYLE=menu

4. Найдите строку GRUB_TIMEOUT=5 и измените значение на то, которое вам нужно. Это определяет количество секунд задержки перед автоматической загрузкой дефолтной операционной системы.

5. Добавьте следующую строку, чтобы настроить цвет фона главного меню grub2:

GRUB_BACKGROUND="/путь/к/изображению/background.jpg"

Замените /путь/к/изображению/background.jpg на путь к изображению, которое вы хотите использовать в качестве фона. Изображение должно быть в формате jpg.

6. Нажмите Ctrl + O, чтобы сохранить изменения, а затем нажмите Ctrl + X, чтобы выйти из редактора nano.

7. Обновите файл конфигурации grub2, выполнив следующую команду:

sudo update-grub

Теперь вы успешно отредактировали файл конфигурации grub2 для добавления Windows в меню загрузки. После перезагрузки вашей системы вы увидите новую опцию для загрузки Windows.

Шаг 4: Перезапуск grub2 для применения изменений

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

1. Откройте терминал или консоль суперпользователя.

2. Введите команду:

sudo update-grub

3. Нажмите Enter и дождитесь завершения обновления grub2.

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

Шаг 5: Проверка добавления Windows в grub2

После выполнения предыдущих шагов, добавление Windows в grub2 должно быть завершено. Теперь давайте проверим, правильно ли Windows была добавлена в меню grub2.

  1. Перезагрузите компьютер. При появлении экрана загрузки выберите операционную систему Linux.
  2. Дождитесь, пока Linux загрузится полностью.
  3. Откройте терминал и выполните команду sudo update-grub. Это обновит конфигурацию grub2.
  4. Перезагрузите компьютер и при появлении экрана загрузки выберите «Advanced options for Ubuntu».
  5. В списке доступных ядер Linux найдите «Windows Boot Manager».
  6. Выберите «Windows Boot Manager» и нажмите Enter, чтобы запустить Windows.

Если Windows успешно запускается после выбора «Windows Boot Manager» в меню grub2, это означает, что Windows была успешно добавлена в grub2. Вы можете перезапустить компьютер еще раз для дополнительной проверки.

If you install Ubuntu first and Windows later, you’ll notice that it’s not possible to boot into Linux anymore. As Windows boot loader doesn’t really handle Linux, you’ll need to tell Windows to use Grub.

Once you’re in command prompt with administrative privileges, you can execute:

CMD

bcdedit /set {bootmgr} path \EFI\Ubuntu\grubx64.efi

After reboot Grub will show it’s ugly face and you’ll have another problem — there are no Windows entries.

To get them into Grub menu, one can simply update grub:

Terminal

sudo update-grub

On most Linux distributions this will trigger OS Prober and Windows Boot Manager entry will magically appear. However, if you have OS Prober disabled or you want to disable it in future for some reason, you can add manual entry too:

Terminal

cat << EOF | sudo tee /etc/grub.d/25_windows
#!/bin/sh
exec tail -n +3 \$0
menuentry 'Windows 10' {
savedefault
search --no-floppy --set=root --file /EFI/Microsoft/Boot/bootmgfw.efi
chainloader (\${root})/EFI/Microsoft/Boot/bootmgfw.efi
}
EOF

sudo chmod +x /etc/grub.d/25_windows

sudo update-grub

In either case, boot menu should now offer you option to get into Windows.

Другие наши интересноые статьи:

  • Add gcc to path windows
  • Add type assemblyname system windows forms
  • Adguard for windows в автозагрузке что это
  • Adguard vpn premium скачать windows
  • Add to your hosts file by default c windows system32 drivers etc hosts these lines

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

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