Proper Treatment 正當作法/ blog/ posts/ Grub default
標籤 Tags:
2010-06-21 16:40

Oh, to hell with all this screwy business with savedefault in Grub 2. Let’s just set the default in userspace.


$ cat /etc/rc.local 
#!/bin/sh -e
#
# rc.local
#
# This script is executed at the end of each multiuser runlevel.
# Make sure that the script will "exit 0" on success or any other
# value on error.
#
# In order to enable or disable this script just change the execution
# bits.
#
# By default this script does nothing.

/usr/bin/perl <<'END'
# Set grub default menu entry by inspecting /proc/cmdline and
# looking for its contents in /boot/grub/grub/cfg
# [ccshan 2010-06-21]
use strict;
my $cmdline;
{
    open my $fh, '<', '/proc/cmdline' or die $!;
    local $/;
    $cmdline = <$fh>;
    close $fh;
}
$cmdline =~ s/\A\s*BOOT_IMAGE=//;
$cmdline =~ s/\s+\z//;
open my $fh, '<', '/boot/grub/grub.cfg' or die $!;
my $title;
while (<$fh>)
{
    if (/^\s*menuentry\s+'([^']*)'/)
    { $title = $1 }
    elsif (defined $title and /^\s*linux\s+(.*\S)/ and $1 eq $cmdline)
    { exec "/usr/sbin/grub-set-default", $title }
}
close $fh;
print STDERR "Cannot find menu entry to set default\n";
END

exit 0

$ cat /etc/default/grub
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.

GRUB_DEFAULT=saved
...