我想创建一个简单的bash循环,它迭代一系列具有特定间隔的数字,然后是不同的数字序列,例如
for i in $(seq 0 5 15)
do
echo $i
done
Run Code Online (Sandbox Code Playgroud)
但是在通过i= 0,5,10,15进行交互之后,我希望它能够反复说出30,35,40,45.
有没有办法使用seq?还是另类?
jub*_*0bs 10
只需在$(...)另一个调用中扩充命令seq:
for i in $(seq 0 5 15; seq 30 5 45); do
echo $i
done
Run Code Online (Sandbox Code Playgroud)
然后
$ bash test.sh
0
5
10
15
30
35
40
45
Run Code Online (Sandbox Code Playgroud)
在你的后续评论中,你写了
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
Run Code Online (Sandbox Code Playgroud)
为了实现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
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
Run Code Online (Sandbox Code Playgroud)