如果输入无效,如何重新运行 case 语句?

8 linux bash shell-script case

我在脚本中间有以下代码来确认我们是否要恢复脚本。

read -r -p "Would you like to continue  [Y/N] : " i
case $i in
        [yY])
                echo -e "Resuming the script";;
        [nN])
                echo -e "Skipped and exit script"
                exit 1;;
        *)
                echo "Invalid Option"
                ;;
esac
Run Code Online (Sandbox Code Playgroud)

我想知道有什么方法可以知道如果输入选项无效,有什么方法可以调用 switch-case 吗?

Kus*_*nda 14

循环输入。如果您收到用户的有效响应,则退出循环break(或exit视情况而定)。

while true; do
    read -p 'Continue? yes/no: ' input
    case $input in
        [yY]*)
            echo 'Continuing'
            break
            ;;
        [nN]*)
            echo 'Ok, exiting'
            exit 1
            ;;
         *)
            echo 'Invalid input' >&2
    esac
done
Run Code Online (Sandbox Code Playgroud)

作为效用函数:

ask_continue () {
    while true; do
        read -p 'Continue? yes/no: ' input        
        case $input in
            [yY]*)
                echo 'Continuing'
                break
                ;;
            [nN]*)
                echo 'Ok, exiting'
                exit 1
                ;;
             *)
                echo 'Invalid input' >&2
        esac
    done
}
Run Code Online (Sandbox Code Playgroud)

允许通过 EOF 退出的效用函数的变体(例如按下Ctrl+D):

ask_continue () {
    while read -p 'Continue? yes/no: ' input; do    
        case $input in
            [yY]*)
                echo 'Continuing'
                return
                ;;
            [nN]*)
                break
                ;;
             *)
                echo 'Invalid input' >&2
        esac
    done

    echo 'Ok, exiting'
    exit 1
}
Run Code Online (Sandbox Code Playgroud)

在这里,有三种退出循环的方式:

  1. 用户输入“yes”,在这种情况下函数返回。
  2. 用户输入“no”,在这种情况下我们break退出循环并执行exit 1
  3. read由于遇到输入结束或其他错误等原因而失败,在这种情况下exit 1执行 。

而不是exit 1您可能想要使用return 1来允许调用者决定当用户不想继续时要做什么。调用代码可能看起来像

if ! ask_continue; then
    # some cleanup, then exit
fi
Run Code Online (Sandbox Code Playgroud)


Rud*_*diC 7

为什么不只是重复阅读?

unset i
while [[ ! "$i" =~ ^[yYnN]$ ]]; do read -r -p "Would you like to continue  [Y/N] : " i; done
Run Code Online (Sandbox Code Playgroud)


Siv*_*iva 2

您可以通过将 switch case 保留在函数内来实现。

function testCase ()
{
    read -r -p "Would you like to continue  [Y/N] : " i
    case $i in
        [yY])
            echo -e "Resuming the script";;
        [nN])
            echo -e "Skipped and exit script"
            exit 1;;
        *)
            echo "Invalid Option"
            testCase
            ;;
    esac
}
testCase
Run Code Online (Sandbox Code Playgroud)

如果输入无效,它将调用该函数,直到获得有效输入。

  • 我不会指望 shell 能够优化尾递归,并且考虑到 shell 脚本通常的过程性质,我真的建议编写该循环。 (8认同)
  • 或者直到遇到资源限制或最大递归深度限制。 (3认同)