【问题标题】:Repeat echo while answer is No回答否时重复回声
【发布时间】:2018-10-19 11:31:45
【问题描述】:

我对 Bash 脚本非常陌生,所以如果问题有些不连贯,请见谅。

如果用户回答“否”,我希望我的脚本重复一个问题 4 次,如果用户回答“是”,那么脚本可以退出,这就是我目前所拥有的

#!/bin/bash
echo "Would you like a cup of tea?"

read answer

while true;

do

        if [ $answer = Y ] then
        echo "Great, I'll make tea now"; then
                break
        if [ $answer = N ] then
        echo "Are you sure?"
        continue
        if [ $answer = N ] then
        echo "Are you sure?"
        continue
        if [ $answer = N ] then
        echo "Are you sure?"
        continue
        if [ $answer = N ] then
        echo "Ok, I give up!"
        exit
fi

【问题讨论】:

    标签: linux bash if-statement while-loop


    【解决方案1】:

    您需要在代码中修复许多问题。我强烈建议您在继续之前先阅读基本教程。

    无论如何,你可以做的最基本的程序是这样的:

    count=0
    while true;
    do
        read -r answer
        if [ "$answer" = "Y" ]; then
            echo "Great, I'll make tea now"
            break
        fi
        if [ "$answer" = "N" ]; then
            echo "Are you sure?"
            count=$((count+1))
            if [ $count = 4 ]; then
                break
            fi
        fi
    done
    

    我们将count 设置为用户提供“N”作为答案的次数,当达到 4 时进行检查,然后中断。

    【讨论】:

    • 感谢 Maroun 的帮助,我花了 3 天的时间来解决这个问题,然后才寻求帮助。我需要研究如何清楚地表达我想要代码做什么。再次感谢
    • @GerryH 不客气。请确保您了解解决方案,如果您有任何问题,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 2017-11-20
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    相关资源
    最近更新 更多