bash 如何在bash脚本中正确循环?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8390379/
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
How to while loop correctly in bash script?
提问by frodo
I have wrote this script which takes a stop and start number and counts out the numbers in between - I am yting to get it to keep increasing no matter whether the "stop" number is reaced or not so it keeps counting until ctrl+z is pressed but it is not recognising the while condition for me - could anyone correct the syntax for me please ?
我写了这个脚本,它需要一个停止和开始的数字,并计算出它们之间的数字 - 我很想让它继续增加,无论“停止”数字是否被重新接收,所以它会一直计数直到 ctrl+z 是按下但它不能识别我的 while 条件 - 任何人都可以为我纠正语法吗?
#!/bin/sh
stopvalue=
startvalue=
if [ $# -ne 2 ]
then
echo "Error - You must enter two numbers exactly - using default start value of 1"
#exit 0
fi
echo ${startvalue:=1}
while (test "$startvalue" -le "$stopvalue" || "$startvalue" -ge "$stopvalue")
do
startvalue=$((startvalue+1))
echo $startvalue
done
回答by Michael Krelin - hacker
Now that you have two answers about the while loop, I'll suggest using for
loop instead:
既然您对 while 循环有了两个答案,我建议改用for
循环:
for((i=$startvalue;i<=$stopvalue;++i)) do
echo $i
done
回答by Tarun Sharma
I use the simple while loop program. Which works for me. as per my understanding before passing any variable in while loop we have to declare it:
我使用简单的 while 循环程序。这对我有用。根据我的理解,在 while 循环中传递任何变量之前,我们必须声明它:
sum=0
temp=1
while [ $temp -ne 0 ]
do
echo "Enter number: OR 0 to Quit :"
read temp
sum=`expr $sum + $temp`
done
echo $sum
回答by Kevin
Your main problem is in your condition:
您的主要问题在于您的状况:
while (test "$startvalue" -le "$stopvalue" || "$startvalue" -ge "$stopvalue")
You are telling it to continue if $startvalue
is (less than or equal to) or (greater than or equal to) $stopvalue
. For ANY combination of $startvalue
and $stopvalue
, the one will be less than, equal to, or greater than the other. Take out the second half so it only continues if $startvalue
is less than or equal to $stopvalue
.
如果$startvalue
是 (小于或等于) 或 (大于或等于),您告诉它继续$stopvalue
。对于任意组合$startvalue
和$stopvalue
,一个将小于,等于或大于另一个。取出后半部分,以便它仅在$startvalue
小于或等于 时继续$stopvalue
。
And you should write it:
你应该写它:
while [ "$startvalue" -le "$stopvalue” ]
回答by Andrew Clark
while [ "$startvalue" -le "$stopvalue" -o "$startvalue" -ge "$stopvalue" ]
do
startvalue=$((startvalue+1))
echo $startvalue
done