对于Bash中的大数序列进行循环 [英] For loop over sequence of large numbers in Bash

查看:39
本文介绍了对于Bash中的大数序列进行循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Bash脚本中,我使用了一个简单的for循环,如下所示:

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

此for循环工作正常.但是,当我想使用更大的数字序列(例如10 ^ 8到10 ^ 12)时,循环似乎不会开始.

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?

推荐答案

问题是 $(seq ...)扩展为 before 单词列表循环被执行.因此,您的初始命令类似于:

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

此"C样式"构造使用终止条件,而不是遍历单词的文字列表.

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

便携式样式,用于POSIX shell:

Portable style, for POSIX shells:

i=100000000
while [ $i -le 1000000000000 ]; do
  echo "$i"
  i=$(( i + 1 ))
done

这篇关于对于Bash中的大数序列进行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆