Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate for loop number sequence by using variable names in bash? [duplicate]

Could anybody explain how can I use variable names in bash for loop to generate a sequence of numbers?

for year in {1990..1997}
do
  echo ${year}
done

Results:

1990 1991 1992 1993 1994 1995 1996 1997

However

year_start=1990
year_end=1997
for year in {${year_start}..${year_end}}
do
  echo ${year}
done

Results:

{1990..1997}

How can I make the second case work? otherwise I have to write tedious while loops. Thanks very much.

like image 728
wiswit Avatar asked May 11 '13 13:05

wiswit


People also ask

How do you loop a variable in a bash script?

To demonstrate, add the following code to a Bash script: #!/bin/bash # Infinite for loop with break i=0 for (( ; ; )) do echo "Iteration: ${i}" (( i++ )) if [[ i -gt 10 ]] then break; fi done echo "Done!"

How do I increment in for loop in shell script?

We increment the variable with +1 in infinite loop.

Can bash variable names have numbers?

Illegal Rules of Name Variables in Bash The variable name having lower case letters. No dollar sign “$” inserted while printing it. Adding spaces after the initialization of the variable name and its value. Start the variable name with number, digit, or special symbols.


2 Answers

You can use something like this

for (( year = ${year_start}; year <=${year_end}; year++ ))
do
  echo ${year}
done

seq command is outdated and best avoided.

http://www.cyberciti.biz/faq/bash-for-loop/

And if you want real bad to use the following syntax,

for year in {${year_start}..${year_end}} 

please modify it as follows:

for year in $(eval echo "{$year_start..$year_end}")

http://www.cyberciti.biz/faq/unix-linux-iterate-over-a-variable-range-of-numbers-in-bash/

Personally, I prefer using for (( year = ${year_start}; year <=${year_end}; year++ )).

like image 136
Bill Avatar answered Sep 16 '22 20:09

Bill


Try following:

start=1990; end=1997; for year in $(seq $start $end); do echo $year; done
like image 27
Sithsu Avatar answered Sep 20 '22 20:09

Sithsu