Saturday, 19 March 2016

shell - How do I iterate over a range of numbers defined by variables in Bash?



How do I iterate over a range of numbers in Bash when the range is given by a variable?



I know I can do this (called "sequence expression" in the Bash documentation):



 for i in {1..5}; do echo $i; done



Which gives:




1
2
3
4
5




Yet, how can I replace either of the range endpoints with a variable? This doesn't work:



END=5
for i in {1..$END}; do echo $i; done



Which prints:




{1..5}



Answer



for i in $(seq 1 $END); do echo $i; done



edit: I prefer seq over the other methods because I can actually remember it ;)


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...