How do I prompt for Yes/No/Cancel input in a Linux shell script?

后端 未结 30 2082
不思量自难忘°
不思量自难忘° 2020-11-22 04:52

I want to pause input in a shell script, and prompt the user for choices.
The standard Yes, No, or Cancel type question.
How d

30条回答
  •  难免孤独
    2020-11-22 05:24

    In response to others:

    You don't need to specify case in BASH4 just use the ',,' to make a var lowercase. Also I strongly dislike putting code inside of the read block, get the result and deal with it outside of the read block IMO. Also include a 'q' for quit IMO. Lastly why type 'yes' just use -n1 and have the press y.

    Example: user can press y/n and also q to just quit.

    ans=''
    while true; do
        read -p "So is MikeQ the greatest or what (y/n/q) ?" -n1 ans
        case ${ans,,} in
            y|n|q) break;;
            *) echo "Answer y for yes / n for no  or q for quit.";;
        esac
    done
    
    echo -e "\nAnswer = $ans"
    
    if [[ "${ans,,}" == "q" ]] ; then
            echo "OK Quitting, we will assume that he is"
            exit 0
    fi
    
    if [[ "${ans,,}" == "y" ]] ; then
            echo "MikeQ is the greatest!!"
    else
            echo "No? MikeQ is not the greatest?"
    fi
    

提交回复
热议问题