Bash seq 在 for 循环中生成两个单独的数字序列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32482421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:32:49  来源:igfitidea点击:

Bash seq to produce two separate sequences of numbers in a for loop

bashfor-loopseq

提问by Lily

I would like to create a simple for bash loop that iterates over a sequence of numbers with a specific interval and then a different sequence of numbers, e.g.

我想创建一个简单的 for bash 循环,它迭代具有特定间隔的数字序列,然后是不同的数字序列,例如

for i in $(seq 0 5 15)
do
    echo $i
done

But after interating through i=0, 5, 10, 15, I'd like it to iterate through say 30, 35, 40, 45 as well.

但是在通过i=0, 5, 10, 15进行交互后,我希望它也能通过 30, 35, 40, 45 进行迭代。

Is there a way to do this using seq? Or an alternative?

有没有办法做到这一点seq?或者替代方案?

回答by jub0bs

Approach 1

方法一

Simply augment the command within $(...)with another call to seq:

只需$(...)通过另一个调用来扩充命令seq

for i in $(seq 0 5 15; seq 30 5 45); do
    echo $i
done

and then

进而

$ bash test.sh
0
5
10
15
30
35
40
45

# Approach 2

# 方法 2

In your follow-up comment, you write

在你的后续评论中,你写

The actual content of the for loop is more than just echo$i(about 200 lines) I don't want to repeat it and make my script huge!

for 循环的实际内容不仅仅是echo$i(大约 200 行)我不想重复它并使我的脚本变得庞大!

As an alternative to the approach outlined above, you could define a shell function for those 200 lines and then call the function in a series of forloops:

作为上述方法的替代方法,您可以为这 200 行定义一个 shell 函数,然后在一系列for循环中调用该函数:

f() {
   # 200 lines
   echo $i
}

for i in $(seq 0 5 15) do
    f
done

for i in $(seq 30 5 45) do
    f
done

Approach 3 (POSIX-compliant)

方法 3(符合 POSIX)

For maximum portability across shells, you should make your script POSIX-compliant. In that case, you need have to eschew seq, because, although many distributions provide that utility, it's not defined by POSIX.

为了最大限度地跨 shell 移植,您应该使脚本符合 POSIX 标准。在这种情况下,您必须避开seq,因为尽管许多发行版都提供了该实用程序,但它并未由 POSIX 定义。

Since you can't use seqto generate the sequence of integers to iterate over, and because POSIX doesn't define numeric, C-style forloops, you have to resort to a whileloop instead. To avoid duplicating the code related to that loop, you can define another function (called custom_for_loopbelow):

由于您不能用于seq生成整数序列以进行迭代,并且因为 POSIX 没有定义数字、C 风格的for循环,所以您必须求助于while循环。为避免重复与该循环相关的代码,您可以定义另一个函数(custom_for_loop如下调用):

custom_for_loop () {
  # : initial value
  # : increment
  # : upper bound
  # : name of a function that takes one parameter
  local i=
  while [ $i -le  ]; do
       $i
      i=$((i+))
  done
}

f () {
    printf "%s\n" ""
}

custom_for_loop 0 5 15 f
custom_for_loop 30 5 45 f