Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grub2 howto increment variable

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?

like image 673
franz86 Avatar asked Sep 02 '25 09:09

franz86


2 Answers

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

like image 187
Sir Athos Avatar answered Sep 05 '25 00:09

Sir Athos


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
like image 24
mrvulcan Avatar answered Sep 04 '25 23:09

mrvulcan