Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular iteration in bash

Tags:

bash

I'd have a couple of possible (say string) values: a b c. I'd like a to switch from one to another in a circular way:

if [ "$value" == "a" ]; then value=b
elif [ "$value" == "b"]; then value=c
elif [ "$value" == "c"]; then value=a
fi

With method like this, Can this be done in a more efficient way, so that I could support many options, like a b c ... z?

like image 279
marmistrz Avatar asked Jun 22 '26 14:06

marmistrz


1 Answers

It can be done like this:

get_next()
{
    __current_i=${__current_i:- 0} # global variable that saves index of current value
    [ $__current_i -ge $# ] && __current_i=0 # if we exceed the number of values, then reset to zero
    shift $__current_i # move to current value
    ((__current_i++)) # increment index
    echo $1
}

val="a b c d"

get_next $val
get_next $val
get_next $val
get_next $val
get_next $val
like image 131
Vasily G Avatar answered Jun 24 '26 03:06

Vasily G



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!