如何从嵌套的 case 语句中跳出 while 循环?

the*_*fog 23 bash shell-script

在下面的脚本中——它会提示用户确认他们想要继续运行一个潜在的错误脚本——当用户Y在提示处输入时——它将跳出case块,只会再次被送回while循环。

#! /bin/bash
set -e

echo
echo "bad install start"
echo "-----------------------------------------"

while true; do
        read -p "this script will probably fail - do you want to run anyway?" yn
        case $yn in
                [Yy]*)
                        ##### WHAT GOES HERE?? #####
                        ;;
                [Nn]*)
                        exit ;;
                *)
                        echo "answer y or n" ;;
        esac

        echo "script has broken out of case back into while loop"
done

echo -e "\e[33m Installing bad packagename \e[0m"
apt-get install sdfsdfdfsd

echo "rest of script - will i keep running?"
Run Code Online (Sandbox Code Playgroud)

n输入的,脚本存在尽如人意。我想知道如何做到这一点,以便在Y输入脚本时同时跳出 thecase while 块,但不会完全退出。我可以为占位符(“这里有什么??”)添加一些东西来做到这一点?

dha*_*hag 41

在用户输入“y”的情况下,您可以同时退出 while 和 case:

break [n]
       Exit from within a for, while, until, or select loop.  If  n  is
       specified, break n levels.  n must be ? 1.  If n is greater than
       the number of enclosing loops, all enclosing loops  are  exited.
       The  return  value is 0 unless n is not greater than or equal to
       1.
Run Code Online (Sandbox Code Playgroud)

在你的情况下,你想做break 2.

  • 在这种情况下,“break”就足够了。我在代码中没有看到两级循环。 (2认同)