I can iterate over multiple ranges / sequences / numbers with constructions like:
for i in $(seq 1 3) 5 $(seq 7 9) 11; do echo $i; done
for i in {1..3} 5 {7..9} 11; do echo $i; done
But how to achieve the same result if ranges / numbers specified in var:
var="{1..3} 5 {7..9} 11"
I found that this can be done with eval
and seq
:
var="seq 1 3; echo 5; seq 7 9; echo 11"; for i in $(eval "$var"); do echo $i; done
Here shown that eval echo
allows to use ranges in vars like (much nicer than the previous one):
var="{1..3} 5 {7..9} 11"; for i in $(eval echo "$var"); do echo $i; done
Is it possible to achieve the same result somehow without using eval
? Or using eval
in this particular case is OK?
Update
Since there are additional overhead with parsing ranges / numbers defined in plain string variable and since I have control over forming such parameter it will be also worth considering solutions for input array var defined like the following:
ranges=( '1 3' 5 '7 9' 11 )
Or even more straightforward and simpler for implementation (but a bit redundant in expression) with using also ranges instead of numbers:
ranges=( '1 3' '5 5' '7 9' '11 11' )
In case of using array with ranges as input string this question becomes pretty simple and boils down to double loop over array with ranges and over each range of this array.
With specifying ranges as array there will be no need of using eval
or parsing string with ranges to array (that have the same but hidden danger of eval
).
var=({1..3} 5 {7..9} 11);for i in "${var[@]}";do echo $i;done
var="{1..3} 5 {7..9} 11"; declare -a "array=($var)"
but you variable are stilleval
uated.