For loop over sequence of large numbers in Bash [duplicate]

夙愿已清 提交于 2021-02-08 06:05:24

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/52609966/for-loop-over-sequence-of-large-numbers-in-bash

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!