在我正在撰寫的腳本中,我嘗試退出第二個嵌套的 while 回圈,而 continue 陳述句似乎被簡單地忽略了,我不確定究竟是為什么。
從手冊:
continue [n]:
Resume the next iteration of the enclosing for, while, until, or select loop. If n is specified,
resume at the nth enclosing loop. n must be ≥ 1. If n is greater than the number of enclosing
loops, the last enclosing loop (the ``top-level'' loop) is resumed. The return value is 0 unless n
is not greater than or equal to 1.
一個說明我的問題的最小示例(ex1.sh):
#!/bin/bash
printf "%d\n" {1..3} | while read i; do
printf "%d\n" {1..3} | while read j; do
sum=$(expr $i $j)
echo "$i $j = $sum"
[ $sum -ge 5 ] && echo continue && continue 2
done
echo 'should only see this for first cycle of i (2 3 >= 5)'
done
輸出ex1.sh:
1 1 = 2
1 2 = 3
1 3 = 4
should only see this for first cycle of i (2 3 >= 5)
2 1 = 3
2 2 = 4
2 3 = 5
continue
should only see this for first cycle of i (2 3 >= 5)
3 1 = 4
3 2 = 5
continue
3 3 = 6
continue
should only see this for first cycle of i (2 3 >= 5)
為什么被continue 2忽視?它清楚地呼應了“繼續”,并且通過運行跟蹤來確認繼續運行的事實set -x
的使用printf顯然很愚蠢ex1.sh,但重現了我在繼續while read x...回圈作業時遇到的問題。
for 回圈按預期作業(ex2.sh):
#!/bin/bash
for i in {1..3}; do
for j in {1..3}; do
sum=$(expr $i $j)
echo "$i $j = $sum"
[ $sum -ge 5 ] && echo continue && continue 2
done
echo 'should only see this for first cycle of i (2 3 >= 5)'
done
輸出ex2.sh:
1 1 = 2
1 2 = 3
1 3 = 4
should only see this for first cycle of i (2 3 >= 5)
2 1 = 3
2 2 = 4
2 3 = 5
continue
3 1 = 4
3 2 = 5
continue
那么,為什么ex1.sh似乎忽略了continue 2內置函式,而ex2.sh行為卻如預期呢?
感謝 M. Nejat Aydin,我自己修復了第一個示例:
#!/bin/bash
while read i; do
while read j; do
sum=$(expr $i $j)
echo "$i $j = $sum"
[ $sum -ge 5 ] && echo continue && continue 2
done < <(printf "%d\n" {1..3})
echo 'should only see this for first cycle of i (2 3 >= 5)'
done < <(printf "%d\n" {1..3})
問題是管道創建子shell,所以我的 continue 陳述句按照手冊的預期表現,在子shell 知道的最外層回圈處繼續。
uj5u.com熱心網友回復:
您的while回圈沒有嵌套。它們在不同的子外殼中運行。continue無法從父 shell 繼續。管道 ( |) 創建子外殼。另一方面,下面的版本應該可以按預期作業,因為兩個whiles 都在同一個 shell 中運行:
while read i; do
while read j; do
sum=$(expr $i $j)
echo "$i $j = $sum"
[ $sum -ge 5 ] && echo continue && continue 2
done < <(printf "%d\n" {1..3})
echo 'should only see this for first cycle of i (2 3 >= 5)'
done < <(printf "%d\n" {1..3})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/422213.html
標籤:
