如何在 BASH 中继续嵌套循环(在第二个内循环之后)?

问题描述 投票:0回答:2

想征求您的意见。

我正在使用 while true、read 和 case 构建带有嵌套循环的交互式 bash 脚本。我的问题是,在第二个内部循环之后(选择“循环 1.3”时),我想继续使用另一个内部循环编写脚本,但它失败了(部分是我对失败的评论)。

我想我在语法中遗漏了一些东西,但找不到它......

下面是脚本的代码。 预先感谢。

#!/bin/bash
while true; do
read -rep $'Loop #1 (outerloop)? \n\tYES\tNO\n\n' yn
case $yn in
    [Yy]* )
    while true; do
    read -rep $'Loop #1.2 (first inner loop)? Please, choose variant 1 or 2.\n\t1\t2\n\n' yn
    case $yn in
    [1]* )
            while true; do
            read -rep $'Loop #1.3 (second inner loop)?\n\tYES\tNO\n\n' yn
            case $yn in
            [Yy]* ) read -rep $'Loop #1.3. Variant Yes.:\n\n' LOOP3Q1; break 3;;
            [Nn]* ) break 3;;
            esac
            done; break 3;;
    [2]* ) 
            while true; do
            read -rep $'Loop #1.3 (second inner loop).\n\tYES\tNO\n\n' yn
            case $yn in
            [Yy]* ) read -rep $'Loop #1.3 variant Yes.\n\n' LOOP3Q2; break 3;;
            [Nn]* ) break 3;;
            esac
            done; break 3;;
# Here it failes. If here I break all loops - it works, but I need to continue...
            echo "Continue loop 1.2 (first inner loop)"
            while true; do
            read -rep $'Loop #1.3 (second inner loop).\n\tYES\tNO\n\n' yn
            case $yn in
            [Yy]* ) read -rep $'Loop #1.3 variant Yes.\n\n' LOOP3Q2; break 3;;
            [Nn]* ) break 3;;
            esac
            done; break 3;
    esac
    done; break 2;;
    Nn]* ) break;;
 esac
 done
bash while-loop case nested-loops interactive-shell
2个回答
3
投票

您无法使用

break
跳入任意循环;参数指定要打破“堆栈”中的多少个循环。


0
投票

这个 bash 脚本帮助我更好地理解如何从嵌套循环继续执行外循环。

基本上,您需要使用

continue [n]
,其中 n 是循环计数 FROM 您要编写的循环 继续 TO 外部循环

#!/bin/bash

for A in {1..2}; do
  echo "Loop A: A$A"
  for B in {1..2}; do
    echo "  Loop B: B$B"
    for C in {1..2}; do
      echo "    Loop C: C$C"
      
      if [[ $C -eq 2 ]]; then
        echo "    Skipping iteration of Loop A from inside Loop C"
        continue 3  # SKIP current iteration on Loop A
      fi
      
      for D in {1..2}; do
        echo "      Loop D: D$D"
        
        if [[ $D -eq 1 ]]; then
          echo "      Skipping iteration of Loop C from inside Loop D"
          continue 2  # SKIP current iteration on Loop C
        fi
        
      done
    done
  done
done

它打印:

Loop A: A1
  Loop B: B1
    Loop C: C1
      Loop D: D1
      Skipping iteration of Loop C from inside Loop D
    Loop C: C2
    Skipping iteration of Loop A from inside Loop C
Loop A: A2
  Loop B: B1
    Loop C: C1
      Loop D: D1
      Skipping iteration of Loop C from inside Loop D
    Loop C: C2
    Skipping iteration of Loop A from inside Loop C
© www.soinside.com 2019 - 2024. All rights reserved.