Simple script to list grub os's and boot one.

Post your Gambas programming questions here.
Post Reply
User avatar
BruceSteers
Posts: 1884
Joined: Thursday 23rd July 2020 5:20pm
Location: Isle of Wight
Contact:

Simple script to list grub os's and boot one.

Post by BruceSteers »

here is a simple script the utilizes the grub-reboot command to select what os to boot into the next boot only. (useful if you have a few test OS's to choose from)

It reads grub.cfg and gets the main entries then lists them.
Double click an os to have it as the next boot os. then after rebooting out of that os it reverts to the default.

Note.
/etc/default/grub file MUST have the default line set to "saved" like this...

GRUB_DEFAULT=saved
if you changed the default to saved from something else then you have to run update-grub

then save this script somewhere, set it's exe flag and launch it.
#!/usr/bin/env gbs3
' Gambas script file

Use "gb.gui"
Use "gb.desktop"

Private fForm As Form
Private lList As ListBox
Private cBox As CheckBox

Private iTextLen As Integer

Public Sub Main()

  Dim sRet As String, aLines As String[]

  With fForm = New Form
    .Spacing = True
    .Margin = True
    .Title = "Select OS to boot next boot"
    .Arrangement = Arrange.Vertical
    .Foreground = Color.Magenta
   End With

  lList = New ListBox(fForm) As "List"
  lList.Font = Font["Ubuntu,16"]
  lList.Expand = True

  aLines = GetMainEntries()

  lList.List = aLines.Copy()
  lList.Background = Color.SetAlpha(Color.Cyan, 220)
  fForm.Width = iTextLen + (Desktop.Scale * 3)
  fForm.Height = (lList.List.Count + 4) * lList.Font.Height
  
  With cBox = New CheckBox(fForm)
  .Text = "Reboot after setting. (no confirmation)"
  End With

  fForm.Show

End

Public Sub List_Activate()

  Desktop.RunAsRoot("grub-reboot \"" & Last.Text & "\"", True)
  fForm.Hide()
  If Not cBox.Value Then
    If Message.Question("Next reboot set to...\n " & Last.Text, "Reboot now", "Reboot Later") <> 1 Then Return
  Endif
  Shell "reboot"
  fForm.Close()

End

Public Sub GetMainEntries() As String[]

  Dim sEntries As New String[]
  Dim sLines As String[] = Split(File.Load("/boot/grub/grub.cfg"), "\n", Null, True)

  Dim bInSub As Boolean
  Dim iDepth As Integer

  For Each s As String In sLines

    If bInSub Then
      If LTrim(s) Begins "menuentry " Then
        Inc iDepth
      Else If Trim(s) = "}" Then
        Dec iDepth
        If iDepth < 0 Then bInsub = False

      Endif
    Else
      If LTrim(s) Begins "menuentry " Then
        sEntries.Add(Split(s, If(InStr(s, "'"), "'", "\""))[1])
        iTextLen = Max(iTextLen, lList.Font.TextWidth(sEntries.Last))
      Else If LTrim(s) Begins "submenu " Then
        Idepth = 0
        bInSub = True
      Endif

    Endif

  Next

  Return sEntries

End
If at first you don't succeed , try doing something differently.
BruceS
Post Reply