[英]Specifying multiple conditions in bash for loop
So I want to pass a for loop in my bash script, and I want it to stop depending on two parameters: 所以我想在我的bash脚本中传递一个for循环,并且我希望它根据两个参数停止:
for (( x=1; x<= 50 -a $array_position -lt ${#array[@]}; x++ ))
do
echo ${array[$array_position]}
array_position=$((array_position+1))
done
My intention is to have this for loop echo 50 consecutive array values [0] -- [50], but stop if $array_position reaches the end of the array before all 50 loop iterations complete. 我的意图是让该循环回送50个连续的数组值[0]-[50],但是如果$ array_position在所有50个循环迭代完成之前到达数组的末尾,则停止。
Any help is appreciated, as always! 一如既往地感谢您的帮助!
The problem is the -a
or -lt
in your for
statement. 问题是您的
for
语句中的-a
或-lt
。 Change it to this: 更改为此:
for (( x=1; x<= 50 && $array_position < ${#array[@]}; x++ ))
Or to simplify the whole thing further: 或进一步简化整个过程:
for (( x=0; x < 50 && x < ${#array[@]}; x++ ))
do
echo "${array[$x]}"
done
You should only need to specify the array size as your test, and use a break statement if you reach 50: 您只需要指定数组大小作为测试,并在达到50时使用break语句:
for (( x=1; x<=${#array[@]}; x++ ))
do
echo ${array[$array_position]}
array_position=$((array_position+1))
[ $x -eq 50 ] && break
done
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.