Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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}

like image 258
eschercycle Avatar asked Oct 04 '08 01:10

eschercycle


People also ask

How do you loop through a range of numbers in bash?

You can iterate the sequence of numbers in bash in two ways. One is by using the seq command, and another is by specifying the range in for loop. In the seq command, the sequence starts from one, the number increments by one in each step, and print each number in each line up to the upper limit by default.

What does %% do in bash?

In your case ## and %% are operators that extract part of the string. ## deletes longest match of defined substring starting at the start of given string. %% does the same, except it starts from back of the string.

How do you define variables in bash and use values?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.

Which loop does bash provide to iterate over a group of values and perform some commands on each one?

Use the for loop to iterate through a list of items to perform the instructed commands.


2 Answers

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

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

like image 170
Jiaaro Avatar answered Sep 18 '22 08:09

Jiaaro


The seq method is the simplest, but Bash has built-in arithmetic evaluation.

END=5 for ((i=1;i<=END;i++)); do     echo $i done # ==> outputs 1 2 3 4 5 on separate lines 

The for ((expr1;expr2;expr3)); construct works just like for (expr1;expr2;expr3) in C and similar languages, and like other ((expr)) cases, Bash treats them as arithmetic.

like image 44
ephemient Avatar answered Sep 18 '22 08:09

ephemient