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

问题描述 投票:7回答:1

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

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

但是在插入i = 0、5、10、15之后,我也希望它也迭代30、35、40、45。

有没有一种方法可以使用seq?还是其他选择?

bash for-loop seq
1个回答
11
投票

方法1

仅通过再次调用$(...)来扩展seq中的命令:

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

然后

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

#方法2

在您的后续评论中,您写

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

作为上述方法的替代方法,您可以为这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

方法3(符合POSIX)

为了获得跨shell的最大可移植性,您应该使脚本符合POSIX。在这种情况下,您需要避免使用seq,因为尽管许多发行版都提供了该实用程序,但POSIX并未定义该实用程序。

由于无法使用seq生成要迭代的整数序列,并且由于POSIX没有定义数字,所以C样式的for循环,因此您不得不求助于while循环。为了避免重复与该循环相关的代码,可以定义另一个函数(以下称为custom_for_loop):

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

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

custom_for_loop  0 5 15 f
custom_for_loop 30 5 45 f
© www.soinside.com 2019 - 2024. All rights reserved.