标签归档:Grub2

GRUB2配置文件"grub.cfg"详解(GRUB2实战手册)

GRUB2模块

对于GRUB-2.0.2版本来说,官方提供的模块一共有200多个,这些模块大致可以分为以下几类(模块间的依赖关系位于"moddep.lst"文件中):

命令模块[command.lst]
提供了各种不同的功能,类似标准Unix命令,一共将近100个。例如:cat cpuid echo halt lspci chainloader initrd linux password ...
加密模块[crypto.lst]
提供了各种数据完整性校验与密码算法支持,一共20多个。例如:gcry_rijndael crc64 gcry_md5 ...
文件系统模块[fs.lst]
提供了访问各种文件系统的功能,一共30多个。例如:btrfs cpio exfat ext2 fat iso9660 ntfs tar xfs zfs ...
分区模块[partmap.lst]
提供了识别各种分区格式的功能,一共10多个。例如:part_bsd part_gpt part_msdos ...
分区工具[parttool.lst]
提供了操作各种分区格式的功能,目前只有 msdospart 这一个。
终端模块[terminal.lst]
提供了各种不同终端的支持,一共不到10个。例如:serial gfxterm vga_text at_keyboard ...
视频模块[video.lst]
提供了各种不同的视频模式支持,一共6个。例如:vga vbe efi_gop efi_uga ...
其他模块
所有未在上述分类文件中列出的模块都归为这一类,一共将近100个。值得关注的有以下几个:

"all_video"可用于一次性加载当前所有可用的视频模块;
"gfxmenu"可用于提供主题支持;
"jpeg png tga"可用于提供特定格式的背景图片支持;
"xzio gzio lzopio"可用于提供特定压缩格式支持(常配合"initrd"命令使用);
"memdisk"可用于提供内存盘支持,常用于配合MEMDISK工具引导各种镜像文件(ISO镜像/软盘镜像/硬盘镜像)。

GRUB2救援模式

GRUB2在BIOS平台上的常规启动步骤是这样的:BIOS --> boot.img[MBR] --> core.img[MBR gap/embedding area/BIOS Boot Partition] --> 设置"prefix root cmdpath"环境变量 --> 加载"normal.mod"模块[同时还包括它所依赖的 terminal crypto extcmd boot gettext 模块] --> 执行"normal $prefix/grub.cfg"命令

GRUB2在UEFI平台上的常规启动步骤是这样的:UEFI --> core.img[BOOTX64.EFI/BOOTX86.EFI] --> 设置"prefix root cmdpath"环境变量 --> 加载"normal.mod"模块[同时还包括它所依赖的 terminal crypto extcmd boot gettext 模块] --> 执行"normal $prefix/grub.cfg"命令

如果上述步骤全部成功,那么你将进入'普通模式',一般是显示一个菜单(找到了'$prefix/grub.cfg'),或者直接进入GRUB SHELL(没找到'$prefix/grub.cfg')。在普通模式中,命令模块[command.lst]与加密模块[crypto.lst]会被自动按需载入(无需使用"insmod"命令),并且可使用完整的GRUB脚本功能。但是其他模块则可能需要明确使用"insmod"命令来载入。

如果在加载"normal.mod"模块这一步出现故障,那么你将进入GRUB2的'救援模式',而不是常规的'普通模式'。在救援模式中,GRUB只自动设置了"cmdpath prefix root"三个环境变量,并且只能使用"insmod ls set unset"四个命令。只有当额外的模块被加载之后,才可以使用一些其它的命令,变量,解析器,驱动程序。通常来说,进入救援模式可能意味着你的GRUB2没有正确安装。请认真阅读'grub-install --help'的输出选项,并使用正确的选项重新安装。更多细节请参考GRUB2手册中的"GRUB only offers a rescue shell"部分。

GRUB2命名规则
设备与分区

GRUB2对设备与分区的命名规则举例如下,看看就能明白。需要说明的是磁盘从"0"开始计数,分区从"1"开始计数。

代码:
(fd0)          第一软盘
(hd0)          第一硬盘[大多数U盘与USB接口的移动硬盘以及SD卡也都被当作硬盘看待]
(hd1,1)        第二硬盘的第一分区(通用于MBR与GPT分区)
(hd0,msdos2)   第一硬盘的第二MBR分区,也就是传统的DOS分区表
(hd1,msdos5)   第二硬盘的第五MBR分区,也就是第一个逻辑分区
(hd0,gpt1)     第一硬盘的第一GPT分区
(cd)           启动光盘[仅在从光盘启动GRUB时可用]
(cd0)          第一光盘
(memdisk)      内存盘[只能有一个]

上面所举的例子仅是最常用的情形,更多高级的设备命名规则请参考GRUB2手册中的"Naming convention"与"How to specify devices"部分。此外,如果你想看看当前系统上有哪些设备可用,可以在GRUB SHELL中使用"ls"命令(可能需要先加载必要的驱动模块)。

文件

文件的命名方法有两种:(1)绝对路径表示法,(2)相对路径表示法。举例如下:

代码:
(fd0)/grldr                 第一软盘根目录下的"grldr"文件[绝对路径]
(hd0,gpt1)/boot/vmlinuz     第一硬盘的第一GPT分区"boot"目录下的"vmlinuz"文件[绝对路径]
/boot/vmlinuz               根设备"boot"目录下的"vmlinuz"文件[相对路径],
当"root"环境变量等于"(hd0,gpt1)"时,等价于"(hd0,gpt1)/boot/vmlinuz"

上面所举的例子仅是最常用的情形,更多高级的文件命名规则请参考GRUB2手册中的"How to specify files"部分。

磁盘块

磁盘块的命名方法同样也有两种:(1)绝对路径表示法,(2)相对路径表示法。举例如下:

代码:
(hd1,1)0+1  在第二硬盘的第一分区上,从第"0"个磁盘块(首扇区)起,长度为"1"的连续块。[绝对路径]
(hd1,1)+1   含义与上一个相同,因为当从第"0"个磁盘块(首扇区)起时,"0"可以省略不写。[绝对路径]
+1          在根设备上,从第"0"个磁盘块(首扇区)起,长度为"1"的连续块。[相对路径]
当"root"环境变量等于"(hd1,1)"时,等价于"(hd1,1)0+1"

磁盘块几乎只用于链式引导(chainloader)的场合。更多高级的磁盘块命名规则请参考GRUB2手册中的"How to specify block lists"部分。

GRUB2环境变量

GRUB2的环境变量大致可以分为两类,第一类是自动设置的变量,也就是这些变量的初始值由GRUB2自动设置,其值必定存在且不为空。第二类是手动设置的变量,它们没有初始值(或者初始值为空),需要经过手动明确设置之后才能使用。

大多数有特定含义的环境变量都是附属于特定附加模块的,只有加载了这些模块之后,这些环境变量才变得有意义。所以从模块的角度看,GRUB2的环境变量又可以分为三类:(1)核心变量,GRUB2核心提供的变量,不依赖于任何可加载模块,这样的变量只有"cmdpath prefix root"三个,而且它们的初始值都由GRUB2自动设置。(2)模块变量,绝大多数有特定含义的环境变量都属此类。(3)脚本变量,这是为了方便编写grub.cfg脚本而设置的变量,没有特殊含义,也不依赖于特定模块,与一般的bash脚本中的变量类似。有关GRUB2脚本的完整说明可以参考GRUB2手册中的"Writing full configuration files directly"部分,基本上其语法与bash脚本完全一致,上手非常容易。
特殊变量

下面列出的变量都是有特定含义的变量,这里只列出常用的一些变量,完整的列表可以参考GRUB2手册中的"Special environment variables"部分。

?
上一条命令的返回值,零表示成功,非零表示失败[与bash一样]。由GRUB2自动设置。你只能使用此变量,而不能修改它。
check_signatures
是否在加载文件时强制验证签名,可以设为'yes'或'no'
chosen
当前被执行的菜单项名称(紧跟"menuentry"命令之后的字符串或者'--id'选项的参数),例如'Windows 7'。由GRUB2自动设置。你只应该使用此变量,而不应该修改它。
cmdpath
当前被加载的"core.img"所在目录(绝对路径)。例如:UEFI启动可能是'(hd0,gpt1)/EFI/UBUNTU'或'(cd0)/EFI/BOOT',BIOS启动可能是'(hd0)'。由GRUB2自动设置。你只应该使用此变量,而不应该修改它。
debug
设为'all'时表示开启调试输出[会显示大量信息,谨慎开启]
default
默认选中第几个菜单项(从'0'开始计数)
fallback
如果默认菜单项启动失败,那么就启动第几个菜单项(从'0'开始计数)
gfxmode
设置"gfxterm"模块所使用的视频模式,可以指定一组由逗号或分号分隔的模式以供逐一尝试:每个模式的格式必须是:'auto'(自动检测),'宽x高','宽x高x色深'之一,并且只能使用VBE标准指定的模式[640x480,800x600,1024x768,1280x1024]x[16,24,32]。可以在GRUB SHELL中使用"videoinfo"命令列出当前所有可用模式。默认值是'auto'。
gfxpayload
设置Linux内核启动时的视频模式,可以指定一组由逗号或分号分隔的模式以供逐一尝试:每个模式的格式必须是:'text'(普通文本模式,不能用于UEFI平台),'keep'(继承"gfxmode"的值),'auto'(自动检测),'宽x高','宽x高x色深'之一,并且只能使用VBE标准指定的模式[640x480,800x600,1024x768,1280x1024]x[16,24,32]。在BIOS平台上的默认值是'text',在UEFI平台上的默认值是'auto'。除非你想明确设置Linux控制台的分辨率(要求内核必须"CONFIG_FRAMEBUFFER_CONSOLE=y"),或者打算在BIOS平台上使用图形控制台(要求内核必须"CONFIG_FRAMEBUFFER_CONSOLE=y"),否则不要设置此变量。
gfxterm_font
设置"gfxterm"模块所使用的字体,默认使用所有可用字体
grub_cpu
此GRUB所适用的CPU类型。例如:'i386', 'x86_64'。由GRUB2自动设置。你只应该使用此变量,而不应该修改它。
grub_platform
此GRUB所适用的平台类型。例如:'pc', 'efi'。由GRUB2自动设置。你只应该使用此变量,而不应该修改它。
lang
设置GRUB2的界面语言,必须搭配"locale_dir"变量一起使用。简体中文应设为'zh_CN'。
locale_dir
设置翻译文件(*.mo)的目录,通常是'$prefix/locale',若未明确设置此目录,则禁止国际化。
pager
如果设为'1',那么每一满屏后暂停输出,等待键盘输入。缺省是'',表示不暂停。
prefix
绝对路径形式的'/boot/grub'目录位置(也就是GRUB2的安装目录),例如'(hd0,gpt1)/grub'或'(hd0,msdos2)/boot/grub'。初始值由GRUB在启动时根据"grub-install"在安装时提供的信息自动设置。你只应该使用此变量,而不应该修改它。
root
设置"根设备"。任何未指定设备名的文件都视为位于此设备。初始值由GRUB在启动时根据"prefix"变量的值自动设置。在大多数情况下,你都需要修改它。
superusers
设置一组"超级用户"(使用空格/逗号/分号进行分隔),以开启安全认证的功能。
theme
设置菜单界面的主题风格文件的位置,例如:"/boot/grub/themes/starfield/theme.txt"。关于如何定制界面风格(背景图片/字体/颜色/图标等)的细节,可以参考GRUB2手册中的"Theme file format"部分。
timeout
在启动默认菜单项前,等待键盘输入的秒数。默认值是'5'秒。'0'表示直接启动默认菜单项(不显示菜单),'-1'表示永远等待。

GRUB2命令

对于GRUB-2.0.2版本来说,所有可用的命令有大约200个之多,他们中的绝大多数由各种各样的模块提供。我们没有必要去了解所有这些200个命令,只需要了解一些常用的命令即可(实际上就连官方文档也没有给出全部的命令说明)。更多的命令说明可以参考GRUB2手册中的"The list of available commands"页面中列出的几个二级页面。

menuentry "title" [--class=class …] [--users=users] [--unrestricted] [--hotkey=key] [--id=id] [arg …] { command; … }

定义一个名为"title"的菜单项。当此菜单项被选中时,GRUB将会把环境变量"chosen"的值设为"id"(使用了[--id=id]选项)或"title"(未使用[--id=id]选项),然后执行花括号中的命令列表,如果列表中最后一个命令执行成功,并且已经载入了一个内核,那么将执行"boot"命令。

可以使用 --class 选项指定菜单项所属的"样式类"。从而可以使用指定的主题样式显示菜单项。

可以使用 --users 选项指定只允许特定的用户访问此菜单项。如果没有使用此选项,则表示允许所有用户访问。

可以使用 --unrestricted 选项指明允许所有用户访问此菜单项。

可以使用 --hotkey 选项设置访问此菜单项的热键(快捷键)。"key"可以是一个单独的字母,或者'backspace','tab','delete'之一。

可以使用 --id 选项为此菜单项设置一个全局唯一的标识符。"id"必须由ASCII字母/数字/下划线组成,且不得以数字开头。

[arg …]是可选的参数列表。你可以把它们理解为命令行参数。实际上"title"也是命令行参数,只不过这个参数是个必须参数而已。这些参数都可以在花括号内的命令列表中使用,"title"对应着"$1",其余的以此类推。
terminal_input [--append|--remove] [terminal1] [terminal2] …

如果不带任何选项与参数,则表示列出当前激活的输入终端,以及所有其他可用的输入终端。

可以使用 --append 选项将指定的终端加入到激活的输入终端列表中,所有列表中的终端都可以用于向GRUB提供输入。

可以使用 --remove 选项将指定的终端从激活的输入终端列表中删除。

如果不使用任何选项,但是指定了一个或多个终端参数,则表示将当前激活的输入终端设置为参数指定的终端。
terminal_output [--append|--remove] [terminal1] [terminal2] …

如果不带任何选项与参数,则表示列出当前激活的输出终端,以及所有其他可用的输出终端。

可以使用 --append 选项将指定的终端加入到激活的输出终端列表中,所有列表中的终端都将接受到GRUB的输出。

可以使用 --remove 选项将指定的终端从激活的输出终端列表中删除。

如果不使用任何选项,但是指定了一个或多个终端参数,则表示将当前激活的输出终端设置为参数指定的终端。
authenticate [userlist]

检查当前用户是否位于"userlist"或环境变量"superusers"中。[注意]如果环境变量"superusers"的值为空,此命令将返回'真'。
background_color color

设置当前激活的输出终端的背景颜色。"color"可以使用HTML风格的颜色表示法("#RRGGBB"或"#RGB")。

[注意]仅在使用'gfxterm'作为输出终端的时候,才能改变背景色。
background_image [[--mode 'stretch'|'normal'] file]

将当前激活的输出终端的背景图片设置为"file"文件。除非使用了"--mode 'normal'"选项,否则图片将被自动缩放以填满整个屏幕。

如果不带任何选项与参数,则表示删除背景图片。

[注意]仅在使用'gfxterm'作为输出终端的时候,才能改变背景图片。
boot

启动已经被载入的OS或链式加载器。仅在运行于交互式命令行的时候才是需要的。在一个菜单项结束时是隐含的。
cat [--dos] file

显示文件"file"的内容。如果使用了"--dos"选项,那么"回车/换行符"将被显示为一个简单的换行符。否则,回车符将被显示为一个控制符(<d>)。
chainloader [--force] file

链式加载"file"文件。通常使用磁盘块表示法,例如用'+1'表示当前根分区的第一个扇区。

可以使用 --force 选项强制载入文件,而不管它是否有正确的签名。通常用于加载有缺陷的启动载入器(例如 SCO UnixWare 7.1)。
configfile file

将"file"作为配置文件加载。如果"file"中定义了菜单项,那么立即显示一个包含它们的菜单。

[注意]"file"文件对环境变量所做的任何变更都将在从此文件返回后失效。
cpuid [-l]

检查CPU特性。仅在x86系统上可用。

如果使用了 -l 选项,那么如果CPU是64位则返回真,否则返回假。
drivemap -l|-r|[-s] from_drive to_drive

如果不使用任何选项,表示将"from_drive"映射到"to_drive"。这主要用于链式加载Windows之类的操作系统,因为它们只能从第一个硬盘启动。出于方便的原因,分区后缀将被忽略,因此你可用安全地将"${root}"作为磁盘使用。

可以使用 -s 选项,执行反向映射,也就是交换这两个磁盘。例如: drivemap -s (hd0) (hd1)

可以使用 -l 选项,列出当前已有的映射。

可以使用 -r 选项,把映射重置为默认值,也就是撤销所有当前已有的映射。
echo [-n] [-e] string …

显示所要求的文本并换行(除非使用了 -n 选项)。如果有多个字符串,依次输出它们,并用空格分隔每一个。

和bash的习惯一样,可以在双引号内使用"${var}"来引用变量的值,也可以使用 -e 选项激活对反斜杠转义符的解释( \\ \a \r \n \t ...)。
export envvar

导出环境变量"envvar",以使其对于使用"configfile"命令载入的配置文件可见。
false

不做任何事,只返回一个失败的结果。主要用在if/while之类的控制构造中。
gettext string

把"string"翻译为环境变量"lang"指定的语言。MO格式的翻译文件从环境变量"locale_dir"指定的目录加载。
halt [--no-apm]

关闭计算机。如果指定了 --no-apm 选项,表示不执行APM BIOS调用。否则,计算机使用APM关闭。
help [pattern …]

显示内建命令的帮助信息。如果没有指定"pattern",那么将显示所有可用命令的简短描述。

如果指定了"pattern",那么将只显示名字以这些"pattern"开头的命令的详细帮助信息。
initrd file

为以32位协议启动的Linux内核载入一个"initial ramdisk",并在内存里的Linux设置区域设置合适的参数。

[注意]这个命令必须放在"linux"命令之后使用。
initrd16 file

为以16位协议启动的Linux内核载入一个"initial ramdisk",并在内存里的Linux设置区域设置合适的参数。

[注意]这个命令必须放在"linux16"命令之后使用。
insmod module

载入名为"module"的GRUB2模块。
linux file …

使用32位启动协议从"file"载入一个Linux内核映像,并将其余的字符作为内核的命令行参数逐字传入。

[注意]使用32位启动协议意味着'vga='启动选项将会失效。如果你希望明确设置一个特定的视频模式,那么应该使用"gfxpayload"环境变量。虽然GRUB可以自动地检测某些'vga='参数,并把它们翻译为合适的"gfxpayload"设置,但是并不建议这样做。
linux16 file …

以传统的16位启动协议从"file"载入一个Linux内核映像,并将其余的字符作为内核的命令行参数逐字传入。这通常用于启动一些遵守Linux启动协议的特殊工具(例如MEMDISK)。

[注意]使用传统的16位启动协议意味着:(1)'vga='启动选项依然有效,(2)不能启动纯64位内核(也就是内核必须要'CONFIG_IA32_EMULATION=y'才行)。
loadfont file …

从指定的"file"加载字体,除非使用了绝对路径,否则"file"将被视为"$prefix/fonts/file.pf2"文件。
loopback [-d] device file

将"file"文件映射为"device"回环设备。例如:

loopback loop0 /path/to/image
ls (loop0)/

可以使用 -d 选项,删除先前使用这个命令创建的设备。
ls [arg …]

如果不使用参数,那么列出所有对GRUB已知的设备。

如果参数是包含在括号内的一个设备名,那么列出该设备根目录下的所有文件。

如果参数是以绝对路径给出的目录,那么列出这个目录的内容。
lsfonts

列出已经加载的所有字体
lsmod

列出已经加载的所有模块
normal [file]

进入普通模式,并显示GRUB菜单。[说明]只要当前没有处于救援模式,其实就已经是在普通模式中了,所以通常并不需要明确使用此命令。

在普通模式中,命令模块[command.lst]与加密模块[crypto.lst]会被自动按需载入(无需使用"insmod"命令),并且可使用完整的GRUB脚本功能。但是其他模块则可能需要明确使用"insmod"命令来载入。

如果给出了"file"参数,那么将从这个文件中读入命令(也就是作为"grub.cfg"的替代),否则将从"$prefix/grub.cfg"中读入命令(如果存在的话)。你也可以理解为"file"的默认值是'$prefix/grub.cfg'。

可以在普通模式中嵌套调用此命令,以构建一个嵌套的环境。不过一般不这么做,而是使用"configfile"命令来达到这目的。
normal_exit

退出当前的普通模式。如果这个普通模式实例不是嵌套在另一个普通模式里的话,就会返回到救援模式。
parttool partition commands

对分区表进行各种修改。目前只能作用于MBR分区表(DOS分区表),而不能用于GPT分区表。目前仅支持以下三种用法:

(1)设置或去掉分区的激活标记(仅对Windows系统有意义)。
例如:"parttool (hd0,msdos2) +boot"表示为(hd0,msdos2)分区加上激活标记,而"parttool (hd0,msdos2) -boot"则表示去掉(hd0,msdos2)分区的激活标记。

(2)设置或去掉分区的隐藏标记(仅对Windows系统有意义)。
例如:"parttool (hd0,msdos2) +hidden"表示为(hd0,msdos2)分区加上隐藏标记,而"parttool (hd0,msdos2) -hidden"则表示去掉(hd0,msdos2)分区的隐藏标记。

(3)更改分区的类型。其值必须是0x00-0xFF范围内的值。且应该使用'0xNN'格式的十六进制数。
例如:"parttool (hd0,msdos2) type=0x83"表示将(hd0,msdos2)分区类型修改为'0x83'(Linux分区)。
password user clear-password

定义一个名为user的用户,并使用明文口令'clear-password'。不建议使用此命令。
password_pbkdf2 user hashed-password

定义一个名为user的用户,并使用哈希口令'hashed-password'(通过"grub-mkpasswd-pbkdf2"工具生成)。这是建议使用的命令,因为它安全性更高。
probe [--set var] --driver|--partmap|--fs|--fs-uuid|--label device

提取"device"设备的特定信息。如果使用了 --set 选项,则表示将提取的结果保存在"var"变量中,否则将提取的结果直接显示出来。
read [var]

从用户读取一行输入。如果给定环境变量"var",则把它设为所读取的行(不包括结尾的换行符)。
reboot

重新启动
rmmod module

卸载"module"模块
search [--file|--label|--fs-uuid] [--set [var]] [--no-floppy] name

通过文件[--file]、卷标[--label]、文件系统UUID[--fs-uuid]来查找设备。

如果使用了 --set 选项,那么会将第一个找到的设备设置为环境变量"var"的值。默认的"var"是'root'。

可以使用 --no-floppy 选项来禁止查找软盘设备,因为这些设备非常慢。
set [envvar=value]

将环境变量"envvar"的值设为'value'。如果没有使用参数,则打印出所有环境变量及其值。
source file

直接将"file"文件的内容插入到当前位置。与"configfile"不同,此命令既不切换执行环境,也不会显示一个新的菜单。
test expression
[ expression ]

计算"expression"的值,并在结果为真时返回零值,或者在结果为假时返回非零值,主要用在if/while之类的控制构造中。

可用的"expression"模式如下(与bash类似):

string1 == string2 [string1与string2完全相同]
string1 != string2 [string1与string2不完全相同]
string1 < string2 [string1在字母顺序上小于string2]
string1 <= string2 [string1在字母顺序上小于string2或与string2完全相同]
string1 > string2 [string1在字母顺序上大于string2]
string1 >= string2 [string1在字母顺序上大于string2或与string2完全相同]
integer1 -eq integer2 [integer1等于integer2]
integer1 -ge integer2 [integer1大于或等于integer2]
integer1 -gt integer2 [integer1大于integer2]
integer1 -le integer2 [integer1小于或等于integer2]
integer1 -lt integer2 [integer1小于integer2]
integer1 -ne integer2 [integer1不等于integer2]
prefixinteger1 -pgt prefixinteger2 [剔除非数字字符首部之后,integer1大于integer2]
prefixinteger1 -plt prefixinteger2 [剔除非数字字符首部之后,integer1小于integer2]
file1 -nt file2 [file1的修改时间比file2新]
file1 -ot file2 [file1的修改时间比file2旧]
-d file [file存在并且是一个目录]
-e file [file存在]
-f file [file存在并且不是一个目录]
-s file [file存在并且文件尺寸大于零]
-n string [string的长度大于零]
string [string的长度大于零]
-z string [string的长度等于零]
( expression ) 将expression视为一个整体(分组)
! expression 非(NOT)
expression1 -a expression2 与(AND)
expression1 -o expression2 或(OR)

true

不做任何事,只返回一个成功的结果。主要用在if/while之类的控制构造中。
unset envvar

撤销环境变量"envvar"
videoinfo [[WxH]xD]

列出所有当前可用的视频模式。如果指定了分辨率(或者还附加了色深),那么仅显示与其匹配的模式。

GRUB2安全

在默认情况下,GRUB对于所有可以在物理上进入控制台的人都是可访问的。任何人都可以选择并编辑任意菜单项,并且可以直接访问GRUB SHELL。要启用认证支持,必须将环境变量"superusers"设置为一组用户名(可用空格/逗号/分号作为分隔符),这样,将仅允许"superusers"中的用户使用GRUB命令行、编辑菜单项、以及执行任意菜单项。而其他非"superusers"中的用户,只能执行那些没有设置 --users 选项的菜单,以及那些在 --users 选项中包含了该用户的菜单,但不能使用GRUB命令行、编辑菜单项。下面使用一个配置片段举例说明:

代码:
set superusers="root"
password_pbkdf2 root grub.pbkdf2.sha512.10000.biglongstring
password user1 insecure

menuentry "所有人都可以执行此菜单" --unrestricted {
...
}

menuentry "仅允许超级用户执行此菜单" --users "" {
...
}

menuentry "允许 user1 和超级用户执行此菜单" --users user1 {
...
}

有关GRUB2安全的更多详情,请参考GRUB2手册中的"Security"部分。
GRUB2实用技巧
如何给GRUB2菜单加上背景图?

首先制作一张PNG格式的图片,分辨率最好是"1024x768"以保证较好的兼容性。然后将这张图片放到"$prefix/themes/1024x768.png"("$prefix"是GRUB2的安装目录)。然后在'grub.cfg'中加入如下内容:

set gfxmode=1024x768,auto
insmod gfxterm
insmod png
terminal_output gfxterm
background_image $prefix/themes/1024x768.png

如何让GRUB2显示中文界面(包括显示中文菜单项)?

由于GRUB2在内部使用UTF-8编码,并且所有文本文件(包括'grub.cfg')也都被假定为使用UTF-8编码,为了避免乱码,请务必以UTF-8编码保存'grub.cfg'文件。

set gfxterm_font=unicode
set lang=zh_CN
set locale_dir=$prefix/locale
insmod gfxterm
terminal_output gfxterm
loadfont unicode

如何更改GRUB2的字体?

如果你认为默认的unicode字体在1024x768或更高分辨率的屏幕上显得太小,或者你认为默认的字体不好看,想换换口味,那么如何自己动手制作一个pf2字体呢?那就要用到"grub-mkfont"工具。下面的示例展示了如何从一个ttc字体(文泉驿等宽微米黑)制作一个24px大小的pf2字体:

grub-mkfont -i1 -n WenQuanYiMicroHeiMono24px -o WenQuanYiMicroHeiMono24px.pf2 -s24 -v wqy-microhei.ttc

将制作好的字体文件(WenQuanYiMicroHeiMono24px.pf2)放到"$prefix/fonts"目录中,修改'grub.cfg'文件中的两行:

set gfxterm_font=WenQuanYiMicroHeiMono24px
loadfont WenQuanYiMicroHeiMono24px

[注意]你最好使用等宽中文字体(推荐使用文泉驿等宽正黑或者等宽微米黑),否则可能会让GRUB2的字体间距过大,十分难看。
如何使用GRUB2引导WindowsPE的ISO文件?

GRUB4DOS有一个非常cool的'磁盘映射'功能,能够用于启动WinPE的ISO文件。其实,将GRUB2的"memdisk"模块配合MEMDISK工具使用,同样可以引导各种镜像文件,包括ISO文件与软/硬盘镜像。

首先,你必须安装或者下载"syslinux"软件包,从中提取出"memdisk"文件(位于'/usr/share/syslinux/memdisk'或'bios/memdisk/memdisk'),然后将它复制到GRUB2的安装目录中,也就是位于"$prefix/memdisk"。

然后,再将你想要引导的WindowsPE的ISO文件放到某个地方,这里假定你和"memdisk"放在一起,也就是位于"$prefix/WinPE.ISO"。当然,为了节约磁盘空间,你也可以用gzip对ISO文件进行压缩,不过这个示例中没有这么做。

最后,在'grub.cfg'中加入如下菜单项(如果你对ISO进行了gzip压缩,那么还需要额外再加上"insmod gzio"命令):

menuentry "Windows PE" --unrestricted {
insmod memdisk
linux16 $prefix/memdisk iso raw
initrd16 $prefix/WinPE.ISO
}

[注意]与GRUB4DOS一样,由于"memdisk"对各种镜像文件的模拟是通过在实模式下拦截BIOS的 INT 13h 与 INT 15h 调用来实现的,所以有很大的局限性:

只能用于BIOS模式启动,不能用于UEFI模式启动
模拟出来的软盘/光盘/硬盘设备只能被基于实模式的操作系统所识别(DOS,FreeDOS),不能被基于保护模式的操作系统所识别(Windows,Linux,BSD)
从实用的角度来说,只能用于引导WinPE的ISO以及基于DOS/FreeDOS的镜像,不能用于引导各种Linux的LiveCD ISO

如何使用GRUB2引导Linux LiveCD的ISO文件?

首先需要说明的是,这里给出的方法,只适用于提供了"iso-scan/filename="或"findiso="之类参数的Linux LiveCD,不适用于未提供此类参数的LiveCD(例如Gentoo)。

下面以最常见的'Ubuntu LiveCD'为例说明。首先,假定你将ISO文件放在'(hd0,gpt3)/ISO/Ubuntu.iso';然后,在'grub.cfg'中加入如下菜单项:

menuentry "Ubuntu LiveCD" --unrestricted {
loopback loop0 (hd0,gpt3)/ISO/Ubuntu.iso
set root=(loop0)
linux /casper/vmlinuz.efi boot=casper iso-scan/filename=/ISO/Ubuntu.iso ro locale=zh_CN.UTF-8
initrd /casper/initrd.lz
}

[说明]这里给出的方法,其实就是各种"硬盘安装XX Linux"的翻版,只不过不再需要将"vmlinuz"与"initrd"从ISO中解压出来而已。

"grub.cfg"实例

下面是本文作者实际使用的一个"grub.cfg"文件,通用于BIOS与UEFI模式,放在这里当作一个实例,供读者参考:

代码:
#################
## (1)特殊变量 ##
#################
#默认启动第一个菜单项
set default=0
#如果第一个菜单项启动失败,转而启动第二个菜单项
set fallback=1
#优先使用最常规的1024x768分辨率,以保证在不同的屏幕上拥有一致的菜单效果,如果失败再自动匹配分辨率
set gfxmode=1024x768,auto
#使用自己制作的24px的大号字体以避免默认字体太小看不清
set gfxterm_font=WenQuanYiMicroHeiMono24px
#将GRUB2设置为简体中文界面
set lang=zh_CN
#指定翻译文件(*.mo)的目录,若未明确设置此目录,则无法显示中文界面。
set locale_dir=$prefix/locale
#每一满屏后暂停输出,以免信息太多一闪而过看不清
set pager=1
#开启密码验证功能,并设置一个名为'root'的超级用户
set superusers=root
#设置菜单的超时时间为5秒
set timeout=5

#################
## (2)公共模块 ##
#################
#两种最流行的磁盘分区格式
insmod part_gpt
insmod part_msdos
#常见文件系统驱动
insmod btrfs
insmod exfat
insmod ext2
insmod fat
insmod iso9660
insmod jfs
insmod ntfs
insmod reiserfs
insmod udf
insmod xfs
insmod zfs
#一次性加载所有可用的视频驱动
insmod all_video
#图形模式终端
insmod gfxterm
#背景图片支持
insmod png

#########################################
## (3)公共命令(必须放在模块和变量之后) ##
#########################################
#激活图形模式的输出终端,以允许使用中文和背景图
terminal_output  gfxterm
#设置背景图片
background_image $prefix/themes/1024x768.png
#加载自己制作的24px的大号字体文件($prefix/fonts/WenQuanYiMicroHeiMono24px.pf2)
loadfont WenQuanYiMicroHeiMono24px
#设置'root'用户的哈希密码[通过"grub-mkpasswd-pbkdf2"工具生成]
password_pbkdf2 root grub.pbkdf2.sha512.69.7DBCA469F80EA1C0A8A1E2FEBC4F8463.B073C1C89EC1E85309C3D6A1BAFF4356

#################
## (4)菜单项   ##
#################

menuentry '正常启动(Windows)' --unrestricted {
if search --file --set --no-floppy /bootmgr ; then
chainloader +1
elif search --file --set --no-floppy /ntldr ; then
chainloader +1
else
echo '没有找到Windows'
sleep --verbose 5
fi
}

if [ 'pc' == $grub_platform ] ; then
menuentry '系统救援(WinPE)' --users=root {
if search --file --set --no-floppy /OS/WinPE.iso ; then
insmod memdisk
linux16  $prefix/memdisk iso raw
initrd16 /OS/WinPE.iso
fi
}
fi

menuentry 'Ubuntu LiveCD amd64' --users=root {
if search --file --set --no-floppy /OS/Ubuntu.iso ; then
loopback loop0 /OS/Ubuntu.iso
set root=(loop0)
linux  /casper/vmlinuz.efi boot=casper iso-scan/filename=/OS/Ubuntu.iso rootwait ro locale=zh_CN.UTF-8
initrd /casper/initrd.lz
fi
}

menuentry 'Gentoo LiveCD' --users=root {
if search --file --set --no-floppy /OS/gentoo/image.squashfs ; then
if [ -f /livecd -a -f /OS/gentoo/gentoo -a -f /OS/gentoo/gentoo.igz ] ; then
linux  /OS/gentoo/gentoo cdroot looptype=squashfs loop=/OS/gentoo/image.squashfs rootwait doscsi nodmraid nokeymap docache dosshd scandelay slowusb passwd=123
initrd /OS/gentoo/gentoo.igz
fi
fi
}

 

GRUB2 部分介绍

GRUB2 is the next generation of the GRand Unified Bootloader (GRUB). GRUB2 is derived from PUPA which was a research project to investigate the next generation of GRUB. GRUB2 has been rewritten from scratch to clean up everything and provide modularity and portability [1].

In brief, the bootloader is the first software program that runs when a computer starts. It is responsible for loading and transferring control to the Linux kernel. The kernel, in turn, initializes the rest of the operating system.

Contents

Preface

Here is some information that needs to be clarified:

  • The name GRUB officially refers to version 2 of the software, see [2]. If you are looking for the article on the legacy version, see GRUB Legacy.
  • From 1.99-6 onwards, GRUB2 supports Btrfs as root (without a separate /boot filesystem) compressed with either zlib or LZO.
  • For GRUB2 UEFI info, it is recommended to read the UEFIGPT and UEFI Bootloaders pages before reading this page.

Notes for current GRUB Legacy users

  • Upgrade from GRUB Legacy to GRUB2 is the much same as fresh installing GRUB2 which is coveredbelow.
  • There are differences in the commands of GRUB and GRUB2. Familiarize yourself with GRUB2 commands before proceeding (e.g. "find" has been replaced with "search").
  • GRUB2 is now modular and no longer requires "stage 1.5". As a result, the bootloader itself is limited -- modules are loaded from the hard drive as needed to expand functionality (e.g. for LVM or RAID support).
  • Device naming has changed between GRUB and GRUB2. Partitions are numbered from 1 instead of 0 while drives are still numbered from 0, and prefixed with partition-table type. For example, /dev/sda1would be referred to as (hd0,msdos1) (for MBR) or (hd0,gpt1) (for GPT) using GRUB2.

Preliminary Requirements for GRUB2

BIOS systems

GUID Partition Table (GPT) specific instructions

GRUB2 in BIOS-GPT configuration requires a BIOS Boot Partition to embed its core.img in the absence of post-MBR gap in GPT partitioned systems (which is taken over by the GPT Primary Header and Primary Partition table). This partition is used by GRUB2 only in BIOS-GPT setups. No such partition type exists in case of MBR partitioning (at least not for GRUB2). This partition is also not required if the system is UEFI based, as no embedding of bootsectors takes place in that case. Syslinux does not require this partition.

For a BIOS-GPT configuration, create a 1007 KiB partition at the beginning of the disk using cgdisk or GNU Parted with no filesystem. The size of 1007 KiB will allow for the following partition to be correctly alligned at 1024 KiB. If needed, the partition can also be located somewhere else on the disk, but it should be within the first 2 TiB region. Set the partition type to 0xEF02 in gdisk, EF02 in cgdisk or set <BOOT_PART_NUM> bios_grub on in GNU Parted.

Note: This partition should be created before grub-install or grub-setup is run.
Note: gdisk will only allow you to create this partition on the position which will waste the least amount of space (sector 34-2047) if you create it last, after all the other partitions. This is because gdisk will auto-align partitions to 2048-sector boundaries if possible.
Master Boot Record (MBR) specific instructions

Usually the post-MBR gap (after the 512 byte MBR region and before the start of the 1st partition) in many MBR (or msdos disklabel) partitioned systems is 31 KiB when DOS compatibility cylinder alignment issues are satisfied in the partition table. However a post-MBR gap of about 1 to 2 MiB is recommended to provide sufficient room for embedding GRUB2's core.img (FS#24103). It is advisable to use a partitioner which supports 1 MiB partition alignment to obtain this space as well as satisfy other non-512 byte sector issues (which are unrelated to embedding of core.img).

MBR partitioning has better support in other operating systems, such as Microsoft Windows (up to Windows 7) and Haiku, than GPT partitioning. If you dual boot another operating system, consider using MBR partitioning.

A MBR disk may be convertible to GPT if there is a small amount of extra space available. See GUID Partition Table#Convert from MBR to GPT

UEFI systems

Note: It is recommended to read and understand the UEFIGPT and UEFI Bootloaders pages.
Create and Mount the UEFI System Partition

Follow Unified Extensible Firmware Interface#EFI System Partition for instructions on creating a UEFI SYSTEM PARTITION. Then mount the UEFI SYSTEM PARTITION at /boot/efi. If you have mounted the UEFISYS partition in some other mountpoint, replace /boot/efi in the below instructions with that mountpoint:

# mkdir -p /boot/efi
# mount -t vfat <UEFISYS_PART_DEVICE> /boot/efi

Create a <UEFI_SYSTEM_PARTITION>/EFI directory, if it does not exist:

# mkdir -p /boot/efi/EFI

Installation

BIOS systems

Backup Important Data

Although a GRUB(2) installation should run smoothly, it is strongly recommended to keep the GRUB Legacy files before installing grub-bios.

# mv /boot/grub /boot/grub-legacy

Backup the MBR which contains the boot code and partition table (Replace /dev/sdX with your actual disk path)

# dd if=/dev/sdX of=/path/to/backup/mbr_backup bs=512 count=1

Only 446 bytes of the MBR contain boot code, the next 64 contain the partition table. If you do not want to overwrite your partition table when restoring, it is strongly advised to backup only the MBR boot code:

# dd if=/dev/sdX of=/path/to/backup/bootcode_backup bs=446 count=1

If unable to install GRUB2 correctly, see #Restore GRUB Legacy.

Install grub-bios package

The GRUB(2) packages can be installed with pacman (and will replace grub-legacy or grub, if it is installed):

# pacman -S grub-bios
Note: Simply installing the package won't update the /boot/grub/i386-pc/core.img file and the GRUB(2) modules in /boot/grub/i386-pc. You need to update them manually using grub-install as explained below.

Install grub-bios boot files

There are 3 ways to install GRUB(2) boot files in BIOS booting:

Install to 440-byte MBR boot code region

To setup grub-bios in the 440-byte Master Boot Record boot code region, populate the /boot/grubdirectory, generate the /boot/grub/i386-pc/core.img file, embed it in the 31 KiB (minimum size - varies depending on partition alignment) post-MBR gap, and generate the configuration file, run:

# modprobe dm-mod
# grub-install --recheck /dev/sda
# grub-mkconfig -o /boot/grub/grub.cfg

where /dev/sda is the destination of the installation (in this case the MBR of the first SATA disk). If you useLVM for your /boot, you can install GRUB2 on multiple physical disks.

Note: --no-floppy has been removed from grub-install in 2.00~beta2 upstream release, and replaced with --allow-floppy.
Warning: Make sure to check the /boot directory if you use the latter. Sometimes the boot-directoryparameter creates another /boot folder inside of /boot. A wrong install would look like: /boot/boot/grub/.
Install to GPT BIOS Boot Partition

GUID Partition Table disks do not have a reserved "boot track".  Therefore you must create a BIOS Boot Partition (0xEF02) to hold the GRUB core image.

Using GNU Parted, you can set this using a command such as the following:

# parted /dev/disk set <partition-number> bios_grub on

If you are using gdisk, set the partition type to 0xEF02. With partitioning programs that require setting the GUID directly, it should be ‘21686148-6449-6e6f-744e656564454649’ (stored on disk as "!haHdInotNeedEFI" if interpreted as ASCII).

Warning: Be very careful which partition you select when marking it as a BIOS Boot Partition. When GRUB finds a BIOS Boot Partition during installation, it will automatically overwrite part of it. Make sure that the partition does not contain any other data.

To setup grub-bios on a GPT disk, populate the /boot/grub directory, generate the /boot/grub/i386-pc/core.img file, and embed it in the BIOS Boot Partition, run:

# modprobe dm-mod
# grub-install --target=i386-pc --recheck --debug /dev/sda
# mkdir -p /boot/grub/locale
# cp /usr/share/locale/en\@quot/LC_MESSAGES/grub.mo /boot/grub/locale/en.mo

where /dev/sda is the destination of the installation.

Install to Partition or Partitionless Disk
Note: grub-bios (any version - including upstream Bazaar repo) does not encourage installation to a partition boot sector or a partitionless disk like GRUB Legacy or Syslinux does. This kind of setup is prone to breakage, especially during updates, and is not supported by Arch devs.

To set up grub-bios to a partition boot sector, to a partitionless disk (also called superfloppy) or to a floppy disk, run (using for example /dev/sdaX as the /boot partition):

# modprobe dm-mod 
# grub-install --target=i386-pc --recheck --debug --force /dev/sdaX
# chattr -i /boot/grub/i386-pc/core.img
# mkdir -p /boot/grub/locale
# cp /usr/share/locale/en@quot/LC_MESSAGES/grub.mo /boot/grub/locale/en.mo
# chattr +i /boot/grub/i386-pc/core.img

You need to use the --force option to allow usage of blocklists and should not use --grub-setup=/bin/true (which is similar to simply generating core.img).

grub-install will give out warnings like which should give you the idea of what might go wrong with this approach:

/sbin/grub-setup: warn: Attempting to install GRUB to a partitionless disk or to a partition. This is a BAD idea.
/sbin/grub-setup: warn: Embedding is not possible. GRUB can only be installed in this setup by using blocklists. 
                        However, blocklists are UNRELIABLE and their use is discouraged.

Without --force you may get the below error and grub-setup will not setup its boot code in the partition boot sector:

/sbin/grub-setup: error: will not proceed with blocklists

With --force you should get:

Installation finished. No error reported.

The reason why grub-setup does not by default allow this is because in case of partition or a partitionless disk is that grub-bios relies on embedded blocklists in the partition bootsector to locate the /boot/grub/i386-pc/core.img file and the prefix dir /boot/grub. The sector locations of core.imgmay change whenever the filesystem in the partition is being altered (files copied, deleted etc.). For more info see https://bugzilla.redhat.com/show_bug.cgi?id=728742 and https://bugzilla.redhat.com/show_bug.cgi?id=730915.

The workaround for this is to set the immutable flag on /boot/grub/i386-pc/core.img (using chattr command as mentioned above) so that the sector locations of the core.img file in the disk is not altered. The immutable flag on /boot/grub/i386-pc/core.img needs to be set only if grub-bios is installed to a partition boot sector or a partitionless disk, not in case of installation to MBR or simple generation of core.img without embedding any bootsector (mentioned above).

Generate core.img alone

To populate the /boot/grub directory and generate a /boot/grub/i386-pc/core.img file withoutembedding any grub-bios bootsector code in the MBR, post-MBR region, or the partition bootsector, add --grub-setup=/bin/true to grub-install:

# modprobe dm-mod
# grub-install --target=i386-pc --grub-setup=/bin/true --recheck --debug /dev/sda
# mkdir -p /boot/grub/locale
# cp /usr/share/locale/en@quot/LC_MESSAGES/grub.mo /boot/grub/locale/en.mo

You can then chainload GRUB2's core.img from GRUB Legacy or syslinux as a Linux kernel or a multiboot kernel.

Generate GRUB2 BIOS Config file

Finally, generate a configuration for GRUB2 (this is explained in greater detail in the Configuration section):

# grub-mkconfig -o /boot/grub/grub.cfg
Note: The file path is /boot/grub/grub.cfg, NOT /boot/grub/i386-pc/grub.cfg.

If grub(2) complains about "no suitable mode found" while booting, go to #Correct GRUB2 No Suitable Mode Found Error.

If grub-mkconfig fails, convert your /boot/grub/menu.lst file to /boot/grub/grub.cfg using:

# grub-menulst2cfg /boot/grub/menu.lst /boot/grub/grub.cfg

For example:

/boot/grub/menu.lst
default=0
timeout=5

title  Arch Linux Stock Kernel
root   (hd0,0)
kernel /vmlinuz-linux root=/dev/sda2 ro
initrd /initramfs-linux.img

title  Arch Linux Stock Kernel Fallback
root   (hd0,0)
kernel /vmlinuz-linux root=/dev/sda2 ro
initrd /initramfs-linux-fallback.img
/boot/grub/grub.cfg
set default='0'; if [ x"$default" = xsaved ]; then load_env; set default="$saved_entry"; fi
set timeout=5

menuentry 'Arch Linux Stock Kernel' {
  set root='(hd0,1)'; set legacy_hdbias='0'
  legacy_kernel   '/vmlinuz-linux' '/vmlinuz-linux' 'root=/dev/sda2' 'ro'
  legacy_initrd '/initramfs-linux.img' '/initramfs-linux.img'
  
}

menuentry 'Arch Linux Stock Kernel Fallback' {
  set root='(hd0,1)'; set legacy_hdbias='0'
  legacy_kernel   '/vmlinuz-linux' '/vmlinuz-linux' 'root=/dev/sda2' 'ro'
  legacy_initrd '/initramfs-linux-fallback.img' '/initramfs-linux-fallback.img'
}

If you forgot to create a GRUB2 /boot/grub/grub.cfg config file and simply rebooted into GRUB2 Command Shell, type:

sh:grub> insmod legacycfg
sh:grub> legacy_configfile ${prefix}/menu.lst

Boot into Arch and re-create the proper GRUB2 /boot/grub/grub.cfg config file.

Note: This option works only in BIOS systems, not in UEFI systems.

Multiboot in BIOS

Boot Microsoft Windows installed in BIOS-MBR mode
Note: GRUB(2) supports booting bootmgr directly and chainload of partition boot sector is no longer required to boot Windows in a BIOS-MBR setup.
Warning: Take note that it is the system partition that has bootmgr, not your "real" Windows partition (usually C:). When showing all UUIDs with blkid, the system partition is the one with LABEL="SYSTEM RESERVED" and is only about 100 MB in size (much like the boot partition for Arch). Seehttp://en.wikipedia.org/wiki/System_partition_and_boot_partition for more info.

Find the UUID of the NTFS filesystem of the Windows's SYSTEM PARTITION where the bootmgr and its files reside. For example, if Windows bootmgr exists at /media/SYSTEM_RESERVED/bootmgr:

For Windows Vista/7/8:

# grub-probe --target=fs_uuid /media/SYSTEM_RESERVED/bootmgr
69B235F6749E84CE
# grub-probe --target=hints_string /media/SYSTEM_RESERVED/bootmgr
--hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1
Note: grub-probe should be run as root.
Note: For Windows XP, replace bootmgr with ntldr in the above commands.

Then, add the below code to /etc/grub.d/40_custom or /boot/grub/custom.cfg and regenerate grub.cfg with grub-mkconfig as explained above to boot Windows (XP, Vista, 7 or 8) installed in BIOS-MBR mode:

For Windows Vista/7/8:

menuentry "Microsoft Windows Vista/7/8 BIOS-MBR" {
    insmod part_msdos
    insmod ntfs
    insmod search_fs_uuid
    insmod ntldr     
    search --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1 69B235F6749E84CE
    ntldr /bootmgr
}

For Windows XP:

menuentry "Microsoft Windows XP" {
    insmod part_msdos
    insmod ntfs
    insmod search_fs_uuid
    insmod ntldr     
    search --fs-uuid --set=root --hint-bios=hd0,msdos1 --hint-efi=hd0,msdos1 --hint-baremetal=ahci0,msdos1 69B235F6749E84CE
    ntldr /ntldr
}

/etc/grub.d/40_custom can be used as a template to create /etc/grub.d/nn_custom.  Where nn defines the precendence, indicating the order the script is executed.  The order scripts are executed determine the placement in the grub boot menu.

Note: nn should be greater than 06 to ensure necessary scripts are executed first.

UEFI systems

Note: It is recommended to read the UEFIGPT and UEFI Bootloaders pages before reading this part.

Hardware-Specific UEFI Examples

It is well know that different motherboard manufactures implement UEFI differently.  Users experiencing problems getting Grub/EFI to work properly are encouraged to share detailed steps for hardware-specific cases where UEFI booting does not work as described below.  In an effort to keep the parent GRUB article neat and tidy, see the GRUB EFI Examples page for these special cases.

Install grub-uefi package

Note: Unless specified as EFI 1.x , EFI and UEFI terms are used interchangeably to denote UEFI 2.x firmware. Also unless stated explicitly, the instructions are general and not Mac specific. Some of them may not work or may be different in Macs. Apple's EFI implementation is neither a EFI 1.x version nor UEFI 2.x version but mixes up both. This kind of firmware does not fall under any one UEFI Specification version and is therefore not a standard UEFI firmware.

GRUB(2) UEFI bootloader is available in Arch Linux only from version 1.99~rc1. To install, first detect which UEFI firmware arch you have (either x86_64 or i386).

Depending on that, install the appropriate package

For 64-bit aka x86_64 UEFI firmware:

# pacman -S grub-efi-x86_64

For 32-bit aka i386 UEFI firmware:

# pacman -S grub-efi-i386
Note: Simply installing the package will not update the core.efi file and the GRUB(2) modules in the UEFI System Partition. You need to do this manually using grub-install as explained below.

Install grub-uefi boot files

Install to UEFI System Partition
Note: The below commands assume you are using grub-efi-x86_64 (for grub-efi-i386 replace x86_64 with i386 in the below commands).
Note: To do this, you need to boot using UEFI and not the BIOS. If you booted by just copying the ISO file to the USB drive, you will need to follow this guide or grub-install will show errors.

The UEFI system partition will need to be mounted at /boot/efi/ for the GRUB(2) install script to detect it:

# mkdir -p /boot/efi
# mount -t vfat /dev/sdXY /boot/efi

Install GRUB UEFI application to /boot/efi/EFI/arch_grub and its modules to /boot/grub/x86_64-efi (recommended) using:

# modprobe dm-mod
# grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=arch_grub --recheck --debug
# mkdir -p /boot/grub/locale
# cp /usr/share/locale/en\@quot/LC_MESSAGES/grub.mo /boot/grub/locale/en.mo
Note: Without --target or --directory option, grub-install cannot determine for which firmware grub(2) is being installed. In such cases grub-install will show source_dir doesn't exist. Please specify --target or --directory message.

If you want to install grub(2) modules and grub.cfg at the directory /boot/efi/EFI/grub and the grubx64.efi application at /boot/efi/EFI/arch_grub (ie. all the grub(2) uefi files inside the UEFISYS partition itself) use:

# modprobe dm-mod 
# grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=arch_grub --boot-directory=/boot/efi/EFI --recheck --debug
# mkdir -p /boot/efi/EFI/grub/locale
# cp /usr/share/locale/en\@quot/LC_MESSAGES/grub.mo /boot/efi/EFI/grub/locale/en.mo

The --efi-directory option mentions the mountpoint of UEFI SYSTEM PARTITION , --bootloader-idmentions the name of the directory used to store the grubx64.efi file and --boot-directory mentions the directory wherein the actual modules will be installed (and into which grub.cfg should be created).

The actual paths are:

<efi-directory>/<EFI or efi>/<bootloader-id>/grubx64.efi
<boot-directory>/grub/x86_64-efi/<all modules, grub.efi, core.efi, grub.cfg>
Note: the --bootloader-id option does not change <boot-directory>/grub, i.e. you cannot install the modules to <boot-directory>/<bootloader-id>, the path is hard-coded to be <boot-directory>/grub.

In --efi-directory=/boot/efi --boot-directory=/boot/efi/EFI --bootloader-id=grub:

<efi-directory>/<EFI or efi>/<bootloader-id> == <boot-directory>/grub == /boot/efi/EFI/grub

In --efi-directory=/boot/efi --boot-directory=/boot/efi/EFI --bootloader-id=arch_grub:

<efi-directory>/<EFI or efi>/<bootloader-id> == /boot/efi/EFI/arch_grub
<boot-directory>/grub == /boot/efi/EFI/grub

In --efi-directory=/boot/efi --boot-directory=/boot --bootloader-id=arch_grub:

<efi-directory>/<EFI or efi>/<bootloader-id> == /boot/efi/EFI/arch_grub
<boot-directory>/grub == /boot/grub

In --efi-directory=/boot/efi --boot-directory=/boot --bootloader-id=grub:

<efi-directory>/<EFI or efi>/<bootloader-id> == /boot/efi/EFI/grub
<boot-directory>/grub == /boot/grub

The <efi-directory>/<EFI or efi>/<bootloader-id>/grubx64.efi is an exact copy of <boot-directory>/grub/x86_64-efi/core.efi.

Note: In GRUB 2.00, the grub-install option --efi-directory replaces --root-directory and the latter is deprecated.
Note: The options --efi-directory and --bootloader-id are specific to GRUB(2) UEFI.

In all the cases the UEFI SYSTEM PARTITION should be mounted for grub-install to install grubx64.efi in it, which will be launched by the firmware (using the efibootmgr created boot entry in non-Mac systems).

If you notice carefully, there is no <device_path> option (Eg: /dev/sda) at the end of the grub-installcommand unlike the case of setting up GRUB(2) for BIOS systems. Any <device_path> provided will be ignored by the install script as UEFI bootloaders do not use MBR or Partition boot sectors at all.

You may now be able to UEFI boot your system by creating a grub.cfg file by following #Generate GRUB2 UEFI Config file and #Create GRUB2 entry in the Firmware Boot Manager.

Generate GRUB2 UEFI Config file

Finally, generate a configuration for GRUB(2) (this is explained in greater detail in the Configuration section):

# grub-mkconfig -o <boot-directory>/grub/grub.cfg
Note: The file path is <boot-directory>/grub/grub.cfg, NOT <boot-directory>/grub/x86_64-efi/grub.cfg.

If you used --boot-directory=/boot:

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

If you used --boot-directory=/boot/efi/EFI:

# grub-mkconfig -o /boot/efi/EFI/grub/grub.cfg

This is independent of the value of --bootloader-id option.

If GRUB2 complains about "no suitable mode found" while booting, try #Correct GRUB2 No Suitable Mode Found Error.

Create GRUB2 entry in the Firmware Boot Manager

As of grub-efi-x86_64 version 2.00, grub-install automatically tries to create a menu entry in the boot manager. If it doesn't, then see Beginners' Guide#GRUB for instructions to use efibootmgr to create a menu entry. However, the problem is likely to be that you haven't booted your CD/USB in UEFI mode, as inUnified Extensible Firmware Interface#Create UEFI bootable USB from ISO.

Create GRUB2 Standalone UEFI Application

It is possible to create a grubx64_standalone.efi application which has all the modules embeddded in a memdisk within the uefi application, thus removing the need for having a separate directory populated with all the GRUB2 uefi modules and other related files. This is done using the grub-mkstandalone command which is included in grub-common >= 1:1.99-6 package.

The easiest way to do this would be with the install command already mentioned before, but specifying the modules to include. For example:

# grub-mkstandalone --directory="/usr/lib/grub/x86_64-efi/" --format="x86_64-efi" --compression="xz" \
--output="/boot/efi/EFI/arch_grub/grubx64_standalone.efi" <any extra files you want to include>

The grubx64_standalone.efi file expects grub.cfg to be within its $prefix which is (memdisk)/boot/grub. The memdisk is embedded within the efi app. The grub-mkstandlone script allow passing files to be included in the memdisk image to be as the arguments to the script (in <any extra files you want to include>).

If you have the grub.cfg at /home/user/Desktop/grub.cfg, then create a temporary /home/user/Desktop/boot/grub/ directory, copy the /home/user/Desktop/grub.cfg to /home/user/Desktop/boot/grub/grub.cfg, cd into /home/user/Desktop/boot/grub/ and run:

# grub-mkstandalone --directory="/usr/lib/grub/x86_64-efi/" --format="x86_64-efi" --compression="xz" \
--output="/boot/efi/EFI/arch_grub/grubx64_standalone.efi" "boot/grub/grub.cfg"

The reason to cd into /home/user/Desktop/boot/grub/ and to pass the file path as boot/grub/grub.cfg (notice the lack of a leading slash - boot/ vs /boot/ ) is because dir1/dir2/file is included as (memdisk)/dir1/dir2/file by the grub-mkstandalone script.

If you pass /home/user/Desktop/grub.cfg the file will be included as (memdisk)/home/user/Desktop/grub.cfg. If you pass /home/user/Desktop/boot/grub/grub.cfgthe file will be included as (memdisk)/home/user/Desktop/boot/grub/grub.cfg. That is the reason for cd'ing into /home/user/Desktop/boot/grub/ and passing boot/grub/grub.cfg, to include the file as (memdisk)/boot/grub/grub.cfg, which is what grub.efi expects the file to be.

You need to create an UEFI Boot Manager entry for /boot/efi/EFI/arch_grub/grubx64_standalone.efi using efibootmgr. Follow #Create GRUB2 entry in the Firmware Boot Manager.

Multiboot in UEFI

Chainload Microsoft Windows x86_64 UEFI-GPT

Find the UUID of the FAT32 filesystem in the UEFI SYSTEM PARTITION where the Windows UEFI Bootloader files reside. For example, if Windows bootmgfw.efi exists at /boot/efi/EFI/Microsoft/Boot/bootmgfw.efi (ignore the upper-lower case differences since that is immaterial in FAT filesystem):

# grub-probe --target=fs_uuid /boot/efi/EFI/Microsoft/Boot/bootmgfw.efi
1ce5-7f28
# grub-probe --target=hints_string /boot/efi/EFI/Microsoft/Boot/bootmgfw.efi
--hint-bios=hd0,gpt1 --hint-efi=hd0,gpt1 --hint-baremetal=ahci0,gpt1
Note: grub-probe should be run as root.

Then, add this code to /etc/grub.d/40_custom to chainload Windows x86_64 (Vista SP1+, 7 or 8) installed in UEFI-GPT mode:

menuentry "Microsoft Windows Vista/7/8 x86_64 UEFI-GPT" {
    insmod part_gpt
    insmod fat
    insmod search_fs_uuid
    insmod chain
    search --fs-uuid --set=root --hint-bios=hd0,gpt1 --hint-efi=hd0,gpt1 --hint-baremetal=ahci0,gpt1 1ce5-7f28
    chainloader /efi/Microsoft/Boot/bootmgfw.efi
}

Afterwards remake /boot/grub/grub.cfg

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

Configuration

You can also choose to automatically generate or manually edit grub.cfg.

Note: For EFI systems, if GRUB2 was installed with the --boot-directory option set, the grub.cfg file must be placed in the same directory as grubx64.efi. Otherwise, the grub.cfg file goes in /boot/grub/, just like in the BIOS version of GRUB2.
Note: Here is a quite complete description of how to configure GRUB2:http://members.iinet.net/~herman546/p20/GRUB2%20Configuration%20File%20Commands.html

Automatically generating using grub-mkconfig (Recommended)

The GRUB2 menu.lst equivalent configuration files are /etc/default/grub and /etc/grub.d/*grub-mkconfig uses these files to generate grub.cfg. By default the script outputs to stdout. To generate a grub.cfg file run the command:

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

/etc/grub.d/10_linux is set to automatically add menu items for Arch linux that work out of the box, to any generated configuration. Other operating systems may need to be added manually to /etc/grub.d/40_custom or /boot/grub/custom.cfg

Additional arguments

To pass custom additional arguments to the Linux image, you can set the GRUB_CMDLINE_LINUX variable in /etc/default/grub.

For example, use GRUB_CMDLINE_LINUX="resume=/dev/sdaX" where sdaX is your swap partition to enable resume after hibernation.

You can also use GRUB_CMDLINE_LINUX="resume=/dev/disk/by-uuid/${swap_uuid}", where ${swap_uuid}is the UUID of your swap partition.

Multiple entries are separated by spaces within the double quotes.  So, for users who want both resume and systemd it would look like this:GRUB_CMDLINE_LINUX="resume=/dev/sdaX init=/usr/lib/systemd/systemd"

See Kernel parameters for more info.

Manually creating grub.cfg

Warning: Editing this file is strongly not recommended. The file is generated by the grub-mkconfigcommand, and it is best to edit your /etc/default/grub or one of the scripts in the /etc/grub.dfolder.

A basic GRUB config file uses the following options

  • (hdX,Y) is the partition Y on disk X, partition numbers starting at 1, disk numbers starting at 0
  • set default=N is the default boot entry that is chosen after timeout for user action
  • set timeout=M is the time M to wait in seconds for a user selection before default is booted
  • menuentry "title" {entry options} is a boot entry titled title
  • set root=(hdX,Y) sets the boot partition, where the kernel and GRUB modules are stored (boot need not be a separate partition, and may simply be a directory under the "root" partition (/)

An example configuration:

/boot/grub/grub.cfg
# Config file for GRUB2 - The GNU GRand Unified Bootloader
# /boot/grub/grub.cfg

# DEVICE NAME CONVERSIONS
#
#  Linux           Grub
# -------------------------
#  /dev/fd0        (fd0)
#  /dev/sda        (hd0)
#  /dev/sdb2       (hd1,2)
#  /dev/sda3       (hd0,3)
#

# Timeout for menu
set timeout=5

# Set default boot entry as Entry 0
set default=0

# (0) Arch Linux
menuentry "Arch Linux" {
    set root=(hd0,1)
    linux /vmlinuz-linux root=/dev/sda3 ro
    initrd /initramfs-linux.img
}

## (1) Windows
#menuentry "Windows" {
#set root=(hd0,3)
#chainloader +1
#}

Dual-booting

Note: If you want GRUB2 to automatically search for other systems, you may wish to install os-prober.

Using grub-mkconfig

The best way to add other entries is editing the /etc/grub.d/40_custom or /boot/grub/custom.cfg . The entries in this file will be automatically added when running grub-mkconfig.After adding the new lines, run:

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

to generate an updated grub.cfg.

With GNU/Linux

Assuming that the other distro is on partition sda2:

menuentry "Other Linux" {
set root=(hd0,2)
linux /boot/vmlinuz (add other options here as required)
initrd /boot/initrd.img (if the other kernel uses/needs one)
}
With FreeBSD

Requires that FreeBSD is installed on a single partition with UFS. Assuming it is installed on sda4:

menuentry "FreeBSD" {
set root=(hd0,4)
chainloader +1
}
With Windows

This assumes that your Windows partition is sda3. Remember you need to point set root and chainloader to the system reserve partition that windows made when it installed, not the actual partition windows is on. This example works if your system reserve partition is sda3.

# (2) Windows XP
menuentry "Windows XP" {
    set root=(hd0,3)
    chainloader (hd0,3)+1
}

If the Windows bootloader is on an entirely different hard drive than GRUB, it may be necessary to trick Windows into believing that it is the first hard drive. This was possible with drivemap. Assuming GRUB is on hd0 and Windows is on hd2, you need to add the following after set root:

drivemap -s hd0 hd2

With Windows via EasyBCD and NeoGRUB

Since EasyBCD's NeoGRUB currently does not understand the GRUB2 menu format, chainload to it by replacing the contents of your C:\NST\menu.lst file with lines similar to the following:

default 0
timeout 1
title       Chainload into GRUB v2
root        (hd0,7)
kernel      /boot/grub/i386-pc/core.img

Visual Configuration

In GRUB2 it is possible, by default, to change the look of the menu. Make sure to initialize, if not done already, GRUB2 graphical terminal, gfxterm, with proper video mode, gfxmode, in GRUB2. This can be seen in the section #Correct_GRUB2_No_Suitable_Mode_Found_Error. This video mode is passed by GRUB2 to the linux kernel via 'gfxpayload' so any visual configurations need this mode in order to be in effect.

Setting the framebuffer resolution

GRUB2 can set the framebuffer for both GRUB2 itself and the kernel. The old vga= way is deprecated. The preferred method is editing /etc/default/grub as the following sample:

GRUB_GFXMODE=1024x768x32
GRUB_GFXPAYLOAD_LINUX=keep

To generate the changes, run:

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

The gfxpayload property will make sure the kernel keeps the resolution.

Note: If this example does not work for you try to replace gfxmode="1024x768x32" by vbemode="0x105". Remember to replace the specified resolution with one suitable for your screen.
Note: To show all the modes you can use # hwinfo --framebuffer (hwinfo is available in [community]), while at GRUB2 prompt you can use the vbeinfo command.

If this method does not work for you, the deprecated vga= method will still work. Justadd it next to the "GRUB_CMDLINE_LINUX_DEFAULT=" line in /etc/default/grubfor eg: "GRUB_CMDLINE_LINUX_DEFAULT="quiet splash vga=792" will give you a 1024x768 resolution.

You can choose one of these resolutions: 640×480800×6001024×7681280×10241600×12001920×1200

915resolution hack

Some times for Intel graphic adapters neither # hwinfo --framebuffer nor vbeinfo will show you the desired resolution. In this case you can use 915resolution hack. This hack will temporarily modify video BIOS and add needed resolution. See 915resolution's home page

In the following I will proceed with the example for my system. Please adjust the recipe for your needs. First you need to find a video mode which will be modified later. For that, run 915resolution in GRUB2 command shell:

915resolution -l

The output will be something like:

Intel 800/900 Series VBIOS Hack : version 0.5.3
...
Mode 30 : 640x480, 8 bits/pixel
...

Next, our purpose is to overwrite mode 30. (You can choose what ever mode you want.) In the file /etc/grub.d/00_header just before the set gfxmode=${GRUB_GFXMODE} line insert:

915resolution 30 1440 900

Here we are overwriting the mode 30 with 1440x900 resolution. Lastly we need to set GRUB_GFXMODE as described earlier, regenerate GRUB2 configuration file and reboot to test changes:

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

Background image and bitmap fonts

GRUB2 comes with support for background images and bitmap fonts in pf2 format. The unifont font is included in the grub-common package under the filename unicode.pf2, or, as only ASCII characters under the name ascii.pf2.

Image formats supported include tga, png and jpeg, providing the correct modules are loaded. The maximum supported resolution depends on your hardware.

Make sure you have set up the proper framebuffer resolution.

Edit /etc/default/grub like this:

GRUB_BACKGROUND="/boot/grub/myimage"
#GRUB_THEME="/path/to/gfxtheme"
GRUB_FONT="/path/to/font.pf2"
Note: If you have installed GRUB on a separate partition, /boot/grub/myimage becomes /grub/myimage.

To generate the changes and add the information into grub.cfg, run:

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

If adding the splash image was successful, the user will see "Found background image..." in the terminal as the command is executed. If this phrase is not seen, the image information was probably not incorporated into the grub.cfg file.

If the image is not displayed, check:

  • The path and the filename in /etc/default/grub are correct.
  • The image is of the proper size and format (tga, png, 8-bit jpg).
  • The image was saved in the RGB mode, and is not indexed.
  • The console mode is not enabled in /etc/default/grub.
  • The command grub-mkconfig must be executed to place the background image information into the /boot/grub/grub.cfg file.

Theme

Here is an example for configuring Starfield theme which was included in GRUB2 package.

Edit /etc/default/grub

GRUB_THEME="/usr/share/grub/themes/starfield/theme.txt"

Generate the changes:

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

If configuring the theme was successful, you'll see Found theme: /usr/share/grub/themes/starfield/theme.txt in the terminal.Your splash image will usually not be displayed when using a theme.

Menu colors

You can set the menu colors in GRUB2. The available colors for GRUB2 can be found in the GRUB Manual.Here is an example:

Edit /etc/default/grub:

GRUB_COLOR_NORMAL="light-blue/black"
GRUB_COLOR_HIGHLIGHT="light-cyan/blue"

Generate the changes:

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

Hidden menu

One of the unique features of GRUB2 is hiding/skipping the menu and showing it by holding Esc when needed. You can also adjust whether you want to see the timeout counter.

Edit /etc/default/grub as you wish. Here is an example where the comments from the beginning of the two lines have been removed to enable the feature, the timeout has been set to five seconds and to be shown to the user:

GRUB_HIDDEN_TIMEOUT=5
GRUB_HIDDEN_TIMEOUT_QUIET=false

and run:

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

Disable framebuffer

Users who use NVIDIA proprietary driver might wish to disable GRUB2's framebuffer as it can cause problems with the binary driver.

To disable framebuffer, edit /etc/default/grub and uncomment the following line:

GRUB_TERMINAL_OUTPUT=console

and run:

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

Another option if you want to keep the framebuffer in GRUB2 is to revert to text mode just before starting the kernel. To do that modify the variable in /etc/default/grub:

GRUB_GFXPAYLOAD_LINUX=text

and rebuild the configuration as before.

Other Options

LVM

If you use LVM for your /boot, add the following before menuentry lines:

insmod lvm

and specify your root in the menuentry as:

set root=lvm/lvm_group_name-lvm_logical_boot_partition_name 

Example:

# (0) Arch Linux
menuentry "Arch Linux" {
insmod lvm
set root=lvm/VolumeGroup-lv_boot
# you can only set following two lines
linux /vmlinuz-linux root=/dev/mapper/VolumeGroup-root ro
initrd /initramfs-linux.img
}

RAID

GRUB2 provides convenient handling of RAID volumes. You need to add insmod mdraid which allows you to address the volume natively. For example, /dev/md0 becomes:

set root=(md0)

whereas a partitioned RAID volume (e.g. /dev/md0p1) becomes:

set root=(md0,1)

Persistent block device naming

One naming scheme for Persistent block device naming is the use of globally unique UUIDs to detect partitions instead of the "old" /dev/sd*. Advantages are covered up in the above linked article.

Persistent naming via filesystem UUIDs are used by default in GRUB2.

Note: The /boot/grub.cfg file needs regeneration with the new UUID in /etc/default/grub every time a relevant filesystem is resized or recreated. Remember this when modifying partitions & filesystems with a Live-CD.

Whether to use UUIDs is controlled by an option in /etc/default/grub:

# GRUB_DISABLE_LINUX_UUID=true

Either way, do not forget to generate the changes:

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

Using Labels

It is possible to use labels, human-readable strings attached to filesystems, by using the --label option to search. First of all, label your existing partition:

# tune2fs -L <LABEL> <PARTITION>

Then, add an entry using labels. An example of this:

menuentry "Arch Linux, session texte" {
    search --label --set=root archroot
    linux /boot/vmlinuz-linux root=/dev/disk/by-label/archroot ro
    initrd /boot/initramfs-linux.img
}

Recall previous entry

GRUB2 can remember the last entry you booted from and use this as the default entry to boot from next time. This is useful if you have multiple kernels (i.e., the current Arch one and the LTS kernel as a fallback option) or operating systems. To do this, edit /etc/default/grub and change the setting of GRUB_DEFAULT:

GRUB_DEFAULT=saved

This ensures that GRUB will default to the saved entry. To enable saving the selected entry, add the following line to /etc/default/grub:

GRUB_SAVEDEFAULT=true
Note: Manually added menu items, eg Windows in /etc/grub.d/40_custom or /boot/grub/custom.cfg , will need savedefault added. Remember to regenerate your configuration file.

Security

If you want to secure GRUB2 so it is not possible for anyone to change boot parameters or use the command line, you can add a user/password combination to GRUB2's configuration files. To do this, run the command grub-mkpasswd-pbkdf2. Enter a password and confirm it. The output will look like this:

Your PBKDF2 is grub.pbkdf2.sha512.10000.C8ABD3E93C4DFC83138B0C7A3D719BC650E6234310DA069E6FDB0DD4156313DA3D0D9BFFC2846C21D5A2DDA515114CF6378F8A064C94198D0618E70D23717E82.509BFA8A4217EAD0B33C87432524C0B6B64B34FBAD22D3E6E6874D9B101996C5F98AB1746FE7C7199147ECF4ABD8661C222EEEDB7D14A843261FFF2C07B1269A

Then, add the following to /etc/grub.d/00_header:

cat << EOF

set superusers="username"
password_pbkdf2 username <password>

EOF

where <password> is the string generated by grub-mkpasswd_pbkdf2.

Regenerate your configuration file. Your GRUB2 command line, boot parameters and all boot entries are now protected.

This can be relaxed and further customized with more users as described in the "Security" part of the GRUB manual.

Root Encryption

To let GRUB2 automatically add the kernel parameters for root encryption,add cryptdevice=/dev/yourdevice:label to GRUB_CMDLINE_LINUX in /etc/default/grub.

Example with root mapped to /dev/mapper/root:

GRUB_CMDLINE_LINUX="cryptdevice=/dev/sda2:root"

Also, disable the usage of UUIDs for the rootfs:

GRUB_DISABLE_LINUX_UUID=true

Regenerate the configuration.

Boot non-default entry only once

The command grub-reboot is very helpful to boot another entry than the default only once. GRUB2 loads the entry passed in the first command line argument, when the system is rebooted the next time. Most importantly GRUB2 returns to loading the default entry for all future booting. Changing the configuration file or selecting an entry in the GRUB2 menu is not necessary.

Booting an ISO Directly From GRUB2

Edit /etc/grub.d/40_custom or /boot/grub/custom.cfg to add an entry for the target ISO. When finished, update the GRUB menu as with the usual grub-mkconfig -o /boot/grub/grub.cfg (as root).

Arch ISO

Note: The example assumes that the iso is in /archives on hd0,6. Users must adjust the location and hdd/partition in ALL of the lines below to match their systems. However, if booting the ISO from USB on a computer which also has one internal HDD, then it needs to be hd0,Y with sdbY, instead of sdaY.

Example using x86_64

menuentry "Archlinux-2013.01.04-dual.iso" --class iso {
  set isofile="/archives/archlinux-2013.01.04-dual.iso"
  loopback loop (hd0,6)$isofile
  linux (loop)/arch/boot/x86_64/vmlinuz archisolabel=ARCH_201301 img_dev=/dev/sda6 img_loop=$isofile earlymodules=loop
  initrd (loop)/arch/boot/x86_64/archiso.img
}

Example using i686

menuentry "Archlinux-2013.01.04-dual.iso" --class iso {
  set isofile="/archives/archlinux-2013.01.04-dual.iso"
  loopback loop (hd0,6)$isofile
  linux (loop)/arch/boot/i686/vmlinuz archisolabel=ARCH_201301 img_dev=/dev/sda6 img_loop=$isofile earlymodules=loop
  initrd (loop)/arch/boot/i686/archiso.img
}
Tip: For thumbdrives, use Persistent block device names for the "img_dev" kernel parameter. Ex:img_dev=/dev/disk/by-label/CORSAIR

Ubuntu ISO

Note: The example assumes that the iso is in /archives on hd0,6. Users must adjust the location and hdd/partition in the lines below to match their systems.
menuentry "ubuntu-12.04-desktop-amd64.iso" {
    set isofile="/archives/ubuntu-12.04-desktop-amd64.iso"
    loopback loop (hd0,6)$isofile
    linux (loop)/casper/vmlinuz boot=casper iso-scan/filename=$isofile quiet noeject noprompt splash --
    initrd (loop)/casper/initrd.lz
}

Other ISOs

Other working configurations from link Source.

Using the command shell

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

GRUB2 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:

sh:grub>

If there is a more serious problem (e.g. GRUB 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

Pager support

GRUB2 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 GRUB2 command shell type:

sh:grub> set pager=1

GUI configuration tools

Following package may be installed from AUR

  • grub-customizer (requires gettext gksu gtkmm hicolor-icon-theme openssl)

    Customize the bootloader (GRUB2 or BURG)
  • grub2-editor (requires kdelibs)

    A KDE4 control module for configuring the GRUB2 bootloader
  • kcm-grub2 (requires kdelibs python2-qt kdebindings-python)

    This Kcm module manages the most common settings of Grub2.
  • startupmanager (requires gnome-python imagemagick yelp python2 xorg-xrandr)

    GUI app for changing the settings of GRUB, GRUB2, Usplash and Splashy

parttool for hide/unhide

If you have a Windows 9x paradigm with hidden C:\ disks GRUB can hide/unhide it using parttool. For example, to boot the third C:\ disk of three Windows 9x installations on the CLI enter the CLI and:

parttool hd0,1 hidden+ boot-
parttool hd0,2 hidden+ boot-
parttool hd0,3 hidden- boot+
set root=hd0,3
chainloader +1
boot

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 insmodlsset, and unset. This example uses setand insmodset modifies variables and insmod inserts new modules to add functionality.

Before starting, the user must know the location of their /boot partition (be it a separate partition, or a subdirectory under their root):

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

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

To expand console capabilities, insert the linux module:

grub rescue> insmod (hdX,Y)/boot/grub/linux.mod
Note: With a separate boot partition, omit /boot from the path, (i.e. type set prefix=(hdX,Y)/gruband insmod (hdX,Y)/grub/linux.mod).

This introduces the linux and initrd commands, which should be familiar (see #Configuration).

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, again change the lines accordingly:

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

After successfully booting the Arch Linux installation, users can correct grub.cfg as needed and then reinstall GRUB2.

to reinstall GRUB2 and fix the problem completely, changing /dev/sda if needed. See #Bootloader installation for details.

Combining the use of UUIDs and basic scripting

If you like the idea of using UUIDs to avoid unreliable BIOS mappings or are struggling with GRUB's syntax, here is an example boot menu item that uses UUIDs and a small script to direct GRUB to the proper disk partitions for your system. All you need to do is replace the UUIDs in the sample with the correct UUIDs for your system. The example applies to a system with a boot and root partition. You will obviously need to modify the GRUB configuration if you have additional partitions:

 menuentry "Arch Linux 64" {
     # Set the UUIDs for your boot and root partition respectively
     set the_boot_uuid=ece0448f-bb08-486d-9864-ac3271bd8d07
     set the_root_uuid=c55da16f-e2af-4603-9e0b-03f5f565ec4a
   
     # (Note: This may be the same as your boot partition)
   
     # Get the boot/root devices and set them in the root and grub_boot variables
     search --fs-uuid --set=root $the_root_uuid
     search --fs-uuid --set=grub_boot $the_boot_uuid
   
     # Check to see if boot and root are equal.
     # If they are, then append /boot to $grub_boot (Since $grub_boot is actually the root partition)
     if [ $the_boot_uuid == $the_root_uuid] ; then
         set grub_boot=$grub_boot/boot
     fi
   
     # $grub_boot now points to the correct location, so the following will properly find the kernel and initrd
     linux ($grub_boot)/vmlinuz-linux root=/dev/disk/by-uuid/$uuid_os_root ro
     initrd ($grub_boot)/initramfs-linux.img
 }

Troubleshooting

Any troubleshooting should be added here.

Intel BIOS not booting GPT

Some Intel BIOS's require at least one bootable MBR partition to be present at boot, causing GPT-partitioned boot setups to be unbootable.

This can be circumvented by using (for instance) fdisk to mark one of the GPT partitions (preferably the 1007KiB partition you've created for GRUB2 already) bootable in the MBR. This can be achieved, using fdisk, by the following commands: Start fdisk against the disk you're installing, for instance "fdisk /dev/sda", then press "a" and select the partition you wish to mark as bootable (probably #1) by pressing the corresponding number, finally press "w" to write the changes to the MBR.

Note that the bootable-marking must be done in fdisk or similar, not in GParted or others, as they will not set the bootable flag in the MBR.

More information is available here

Enable GRUB2 debug messages

Add:

set pager=1
set debug=all

to grub.cfg.

Correct GRUB2 No Suitable Mode Found Error

If you get this error when booting any menuentry:

error: no suitable mode found
Booting however

Then you need to initialize GRUB2 graphical terminal (gfxterm) with proper video mode (gfxmode) in GRUB2. This video mode is passed by GRUB2 to the linux kernel via 'gfxpayload'. In case of UEFI systems, if the GRUB2 video mode is not initialized, no kernel boot messages will be shown in the terminal (atleast until KMS kicks in).

Copy /usr/share/grub/unicode.pf2 to ${GRUB2_PREFIX_DIR} (/boot/grub/ in case of BIOS and UEFI systems). If GRUB2 UEFI was installed with --boot-directory=/boot/efi/EFI set, then the directory is /boot/efi/EFI/grub/:

# cp /usr/share/grub/unicode.pf2 ${GRUB2_PREFIX_DIR}

If /usr/share/grub/unicode.pf2 does not exist, install bdf-unifont, create the unifont.pf2 file and then copy it to ${GRUB2_PREFIX_DIR}:

# grub-mkfont -o unicode.pf2 /usr/share/fonts/misc/unifont.bdf

Then, in the grub.cfg file, add the following lines to enable GRUB2 to pass the video mode correctly to the kernel, without of which you will only get a black screen (no output) but booting (actually) proceeds successfully without any system hang.

BIOS systems:

insmod vbe

UEFI systems:

insmod efi_gop
insmod efi_uga

After that add the following code (common to both BIOS and UEFI):

insmod font
if loadfont ${prefix}/fonts/unicode.pf2
then
    insmod gfxterm
    set gfxmode=auto
    set gfxpayload=keep
    terminal_output gfxterm
fi

As you can see for gfxterm (graphical terminal) to function properly, unicode.pf2 font file should exist in ${GRUB2_PREFIX_DIR}.

msdos-style error message

grub-setup: warn: This msdos-style partition label has no post-MBR gap; embedding won't be possible!
grub-setup: warn: Embedding is not possible. GRUB can only be installed in this setup by using blocklists.
            However, blocklists are UNRELIABLE and its use is discouraged.
grub-setup: error: If you really want blocklists, use --force.

This error may occur when you try installing GRUB2 in a VMware container. Read more about it here. It happens when the first partition starts just after the MBR (block 63), without the usual space of 1 MiB (2048 blocks) before the first partition. Read #Master Boot Record (MBR) specific instructions

UEFI GRUB2 drops to shell

If GRUB loads but drops you into the rescue shell with no errors, it may be because of a missing or misplaced grub.cfg. This will happen if GRUB2 UEFI was installed with --boot-directory and grub.cfg is missing OR if the partition number of the boot partition changed (which is hard-coded into the grubx64.efifile).

UEFI GRUB2 not loaded

In some cases the EFI may fail to load GRUB correctly. Provided everything is set up correctly, the output of:

efibootmgr -v

might look something like this:

BootCurrent: 0000
Timeout: 3 seconds
BootOrder: 0000,0001,0002
Boot0000* Grub	HD(1,800,32000,23532fbb-1bfa-4e46-851a-b494bfe9478c)File(\efi\grub\grub.efi)
Boot0001* Shell	HD(1,800,32000,23532fbb-1bfa-4e46-851a-b494bfe9478c)File(\EfiShell.efi)
Boot0002* Festplatte	BIOS(2,0,00)P0: SAMSUNG HD204UI

If everything works correctly, the EFI would now automatically load GRUB.

If the screen only goes black for a second and the next boot option is tried afterwards, according to this post, moving GRUB to the partition root can help. The boot option has to be deleted and recreated afterwards. The entry for GRUB should look like this then:

Boot0000* Grub	HD(1,800,32000,23532fbb-1bfa-4e46-851a-b494bfe9478c)File(\grub.efi)

Invalid signature

If trying to boot Windows results in an "invalid signature" error, e.g. after reconfiguring partitions or adding additional hard drives, (re)move GRUB's device configuration and let it reconfigure:

# mv /boot/grub/device.map /boot/grub/device.map-old
# grub-mkconfig -o /boot/grub/grub.cfg

grub-mkconfig should now mention all found boot options, including Windows. If it works, remove /boot/grub/device.map-old.

Boot freezes

If booting gets stuck without any error message after grub2 loading the kernel and the initial ramdisk, try removing the add_efi_memmap kernel parameter.

Restore GRUB Legacy

  • Move GRUB2 files out of the way:
# mv /boot/grub /boot/grub.nonfunctional
  • Copy GRUB Legacy back to /boot:
# cp -af /boot/grub-legacy /boot/grub
  • Replace MBR and next 62 sectors of sda with backed up copy
Warning: This command also restores the partition table, so be careful of overwriting a modified partition table with the old one. It will mess up your system.
# dd if=/path/to/backup/first-sectors of=/dev/sdX bs=512 count=1

A safer way is to restore only the MBR boot code use:

# dd if=/path/to/backup/mbr-boot-code of=/dev/sdX bs=446 count=1

References

  1. Official GRUB2 Manual - https://www.gnu.org/software/grub/manual/grub.html
  2. Ubuntu wiki page for GRUB2 - https://help.ubuntu.com/community/Grub2
  3. GRUB2 wiki page describing steps to compile for UEFI systems -https://help.ubuntu.com/community/UEFIBooting
  4. Wikipedia's page on BIOS Boot partition

External Links

  1. A Linux Bash Shell script to compile and install GRUB(2) for BIOS from BZR Source
  2. A Linux Bash Shell script to compile and install GRUB(2) for UEFI from BZR Source

`configure' configures GRUB 2.00 说明

`configure' configures GRUB 2.00 to adapt to many kinds of systems.

Usage: ./configure [OPTION]... [VAR=VALUE]...

To assign environment variables (e.g., CC, CFLAGS...), specify them as
VAR=VALUE.  See below for descriptions of some of the useful variables.

Defaults for the options are specified in brackets.

Configuration:
  -h, --help              display this help and exit
      --help=short        display options specific to this package
      --help=recursive    display the short help of all the included packages
  -V, --version           display version information and exit
  -q, --quiet, --silent   do not print `checking ...' messages
      --cache-file=FILE   cache test results in FILE [disabled]
  -C, --config-cache      alias for `--cache-file=config.cache'
  -n, --no-create         do not create output files
      --srcdir=DIR        find the sources in DIR [configure dir or `..']

Installation directories:
  --prefix=PREFIX         install architecture-independent files in PREFIX
                          [/usr/local]
  --exec-prefix=EPREFIX   install architecture-dependent files in EPREFIX
                          [PREFIX]

By default, `make install' will install all the files in
`/usr/local/bin', `/usr/local/lib' etc.  You can specify
an installation prefix other than `/usr/local' using `--prefix',
for instance `--prefix=$HOME'.

For better control, use the options below.

Fine tuning of the installation directories:
  --bindir=DIR            user executables [EPREFIX/bin]
  --sbindir=DIR           system admin executables [EPREFIX/sbin]
  --libexecdir=DIR        program executables [EPREFIX/libexec]
  --sysconfdir=DIR        read-only single-machine data [PREFIX/etc]
  --sharedstatedir=DIR    modifiable architecture-independent data [PREFIX/com]
  --localstatedir=DIR     modifiable single-machine data [PREFIX/var]
  --libdir=DIR            object code libraries [EPREFIX/lib]
  --includedir=DIR        C header files [PREFIX/include]
  --oldincludedir=DIR     C header files for non-gcc [/usr/include]
  --datarootdir=DIR       read-only arch.-independent data root [PREFIX/share]
  --datadir=DIR           read-only architecture-independent data [DATAROOTDIR]
  --infodir=DIR           info documentation [DATAROOTDIR/info]
  --localedir=DIR         locale-dependent data [DATAROOTDIR/locale]
  --mandir=DIR            man documentation [DATAROOTDIR/man]
  --docdir=DIR            documentation root [DATAROOTDIR/doc/grub]
  --htmldir=DIR           html documentation [DOCDIR]
  --dvidir=DIR            dvi documentation [DOCDIR]
  --pdfdir=DIR            pdf documentation [DOCDIR]
  --psdir=DIR             ps documentation [DOCDIR]

Program names:
  --program-prefix=PREFIX            prepend PREFIX to installed program names
  --program-suffix=SUFFIX            append SUFFIX to installed program names
  --program-transform-name=PROGRAM   run sed PROGRAM on installed program names

System types:
  --build=BUILD     configure for building on BUILD [guessed]
  --host=HOST       cross-compile to build programs to run on HOST [BUILD]
  --target=TARGET   configure for building compilers for TARGET [HOST]

Optional Features:
  --disable-option-checking  ignore unrecognized --enable/--with options
  --disable-FEATURE       do not include FEATURE (same as --enable-FEATURE=no)
  --enable-FEATURE[=ARG]  include FEATURE [ARG=yes]
  --disable-dependency-tracking  speeds up one-time build
  --enable-dependency-tracking   do not reject slow dependency extractors
  --disable-nls           do not use Native Language Support
  --disable-rpath         do not hardcode runtime library paths
  --disable-largefile     omit support for large files
  --enable-efiemu         build and install the efiemu runtimes
                          (default=guessed)
  --disable-werror        do not use -Werror when building GRUB
  --enable-mm-debug       include memory manager debugging
  --enable-cache-stats    enable disk cache statistics collection
  --enable-grub-emu-usb   build and install the `grub-emu' debugging utility
                          with USB support (default=guessed)
  --enable-grub-emu-sdl   build and install the `grub-emu' debugging utility
                          with SDL support (default=guessed)
  --enable-grub-emu-pci   build and install the `grub-emu' debugging utility
                          with PCI support (potentially dangerous)
                          (default=no)
  --enable-grub-mkfont    build and install the `grub-mkfont' utility
                          (default=guessed)
  --enable-grub-mount     build and install the `grub-mount' utility
                          (default=guessed)
  --enable-device-mapper  enable Linux device-mapper support (default=guessed)
  --enable-libzfs         enable libzfs integration (default=guessed)

Optional Packages:
  --with-PACKAGE[=ARG]    use PACKAGE [ARG=yes]
  --without-PACKAGE       do not use PACKAGE (same as --with-PACKAGE=no)
  --with-platform=PLATFORM
                          select the host platform [[guessed]]
  --with-bootdir=DIR      set the name of /boot directory [[guessed]]
  --with-grubdir=DIR      set the name of grub directory [[guessed]]
  --with-gnu-ld           assume the C compiler uses GNU ld default=no
  --with-libiconv-prefix[=DIR]  search for libiconv in DIR/include and DIR/lib
  --without-libiconv-prefix     don't search for libiconv in includedir and libdir
  --with-libintl-prefix[=DIR]  search for libintl in DIR/include and DIR/lib
  --without-libintl-prefix     don't search for libintl in includedir and libdir
  --without-included-regex
                          don't compile regex; this is the default on systems
                          with recent-enough versions of the GNU C Library
                          (use with caution on other systems).

Some influential environment variables:
  CC          C compiler command
  CFLAGS      C compiler flags
  LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
              nonstandard directory <lib dir>
  LIBS        libraries to pass to the linker, e.g. -l<library>
  CPPFLAGS    (Objective) C/C++ preprocessor flags, e.g. -I<include dir> if
              you have headers in a nonstandard directory <include dir>
  YACC        The `Yet Another Compiler Compiler' implementation to use.
              Defaults to the first program found out of: `bison -y', `byacc',
              `yacc'.
  YFLAGS      The list of arguments that will be passed by default to $YACC.
              This script will default YFLAGS to the empty string to avoid a
              default value of `-d' given by some make applications.
  CPP         C preprocessor
  CCAS        assembler compiler command (defaults to CC)
  CCASFLAGS   assembler compiler flags (defaults to CFLAGS)

Use these variables to override the choices made by `configure' or to help
it to find libraries and programs with nonstandard names/locations.

grub-mkimage说明

SYNOPSIS
       grub-mkimage [OPTION]... [MODULES]
DESCRIPTION
       Make a bootable image of GRUB.
       -d, --directory=DIR
              use images and modules under DIR [default=/usr/lib/grub/i386-pc]
       -p, --prefix=DIR
              set grub_prefix directory [default=/boot/grub]
       -m, --memdisk=FILE
              embed FILE as a memdisk image
       -f, --font=FILE
              embed FILE as a boot font
       -c, --config=FILE
              embed FILE as boot config
       -o, --output=FILE
              output a generated image to FILE [default=stdout]
       -h, --help
              display this message and exit
       -V, --version
              print version information and exit
       -v, --verbose
              print verbose messages