2

In a Bash script I am using a simple for loop, that looks like:

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

This for loop works fine. However, when I would like to use a sequence of larger numbers (e.g. 10^8 to 10^12), the loop won't seem to start.

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

I cannot imagine, that these numbers are too large to handle. So my question: am I mistaken? Or might there be another problem?

user213544
  • 2,046
  • 3
  • 22
  • 52

1 Answers1

3

The problem is that $(seq ...) is expanded into a list of words before the loop is executed. So your initial command is something like:

for i in 100000000 100000001 100000002 # all the way up to 1000000000000!

The result is much too long, which is what causes the error.

One possible solution would be to use a different style of loop:

for (( i = 100000000; i <= 1000000000000; i++ )) do
  echo "$i"
done

This "C-style" construct uses a termination condition, rather than iterating over a literal list of words.


Portable style, for POSIX shells:

i=100000000
while [ $i -le 1000000000000 ]; do
  echo "$i"
  i=$(( i + 1 ))
done
Tom Fenech
  • 72,334
  • 12
  • 107
  • 141
  • I am having the same problem. however, I want to skip over 1000 numbers. eg. I am trying to do: `for i in $(seq 2380000 1000 2390000); do echo "skip by 1000 value $i"; done` but the output is like: skip by 1000 value 2.38e+06 skip by 1000 value 2.381e+06 skip by 1000 value 2.382e+06 ... My desired output would be: skip by 1000 value 2381000 skip by 1000 value 2382000 skip by 1000 value 2383000... I am doing this on MACOS and so the {2380000..1000..2390000} does not work and hence using 'seq'. Any help will be appreciated – Jenny Mar 21 '19 at 16:34
  • @Jenny I guess your version of `seq` auto-formats the sequence. Perhaps you can pass an argument to specify the format yourself (try `man seq`). Alternatively you could use one of the other types of loop in my answer, adding 1000 instead of 1. – Tom Fenech Mar 25 '19 at 11:04