4

The grub2 shell aims to be a minimalistic bash like shell.

But how can I increment a variable in grub2?

In bash I would do:

var=$((var+1))

or

((var=var+1))

In grub2 I get a syntax error on these calls. How can I achieve this in the grub2 shell?

franz86
  • 103
  • 1
  • 7

2 Answers2

1

Grub2 does not have builtin arithmetic support. You need to add Lua support if you want that, see this answer for details.

Community
  • 1
  • 1
Sir Athos
  • 9,403
  • 2
  • 22
  • 23
  • OK, thanks for your answer! I think I will just add a new grub module for this special case. – franz86 Feb 15 '17 at 09:29
  • Where can one find such information? Granted i have not read the entire GRUB manual, but in the "Shell-like scripting" section no such thing is mentioned. – Enok82 Apr 26 '18 at 09:36
1

Based on this answer (as already linked by other answer), the following appears to work with GRUB's regexp command (allows incrementing from any number 0-5, add more <from>,<to> pairs as needed):

num=0
incr="" ; for x in 0,1 1,2 2,3 3,4 4,5 5,6 ; do 
    regexp --set=1:incr "${num},([0-9]+)" "${x}"
    if [ "$incr" != "" ] ; then 
        echo "$num incremented to $incr" 
        num=$incr
        break 
    fi
done

Decrementing similarly works (just flipping two the regular expression parts):

num=6
decr="" ; for x in 0,1 1,2 2,3 3,4 4,5 5,6 ; do 
    regexp --set=1:decr "([0-9]+),${num}" "${x}"
    if [ "$decr" != "" ] ; then 
        echo "$num decremented to $decr" 
        num=$decr
        break 
    fi
done
mrvulcan
  • 536
  • 4
  • 8