Search code examples
bashseq

Get sequence of numbers in bash without using seq


I want to loop over a sequence of numbers in a BASH script, but the bound values are not constants. I know this syntax:

for year in {2000..2010}; do
  echo ${year}
done

But the values of 2000 and 2010 are changing in my case, so what I am doing right now is this:

for year in `seq ${yeari} ${yeare}`; do
  echo ${year}
done

Is there a bash-native way to do the same, without using seq?


Solution

  • Have a look at man bash:

     for (( expr1 ; expr2 ; expr3 )) ; do list ; done
              First, the arithmetic expression expr1 is evaluated according to
              the rules described  below  under  ARITHMETIC  EVALUATION.   The
              arithmetic  expression  expr2 is then evaluated repeatedly until
              it evaluates to zero.  Each time expr2 evaluates to  a  non-zero
              value,  list  is executed and the arithmetic expression expr3 is
              evaluated.  If any expression is omitted, it behaves  as  if  it
              evaluates to 1.  The return value is the exit status of the last
              command in list that is executed, or false if any of the expres-
              sions is invalid.
    
    for ((i=yeari; i<yeare; i++))
    do
      echo $i
    done
    

    You might possibly also be interested in 'Arithmetic Expansion' ($((expression))) of which you can find more in the man page.