2011-11-30 65 views
1

如何在shell脚本中跳出无限循环while循环首次运行在shell脚本中继续

我想要实现在shell脚本(S)以下PHP代码:

$i=1; 
while(1) { 
    if ($i == 1) continue; 
    if ($i > 9) break; 
    $i++; 
} 
+1

因为你的代码检查$ I == 1,并一直持续到下一次迭代,如果结果为真,增加$我之前,你实际上哈瓦无限循环。 –

+0

你的php代码中有一个无限循环。 – favoretti

回答

0
i=1 
while [ $i -gt 9 ] ; do 
    # do something here 
    i=$(($i+1)) 
done 

是你能做到这一点的方法之一。

HTH

1

break作品在shell脚本为好,但最好要检查的条件while子句中比在循环内,如索尔特建议。假设你有在循环一些更复杂的逻辑检查条件(也就是你真正想要的是do..while循环),你可以做以下之前:

i=1 
while true 
do 
    if [ "$i" -eq 1 ] 
    then 
     continue 
    fi 
    # Other stuff which might even modify $i 
    if [ $i -gt 9 ] 
    then 
     let i+=1 
     break 
    fi 
done 

如果你真的只是想重复的东西$count时候,有一个更简单的方法:

for index in $(seq 1 $count) 
do 
    # Stuff 
done