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

后端 未结 30 1667
不思量自难忘°
不思量自难忘° 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:10

    This is what I usually need in a script/function:

    • default answer is Yes, if you hit ENTER
    • accept also z (in case you mix up you are on QWERTZ Layout)
    • accept other lanyuages ("ja", "Oui", ...)
    • handle the right exit in case you are inside a function
    while true; do
        read -p "Continue [Y/n]? " -n 1 -r -e yn
        case "${yn:-Y}" in
            [YyZzOoJj]* ) echo; break ;;
            [Nn]* ) [[ "$0" = "$BASH_SOURCE" ]] && exit 1 || return 1 ;; # handle exits from shell or function but don't exit interactive shell
            * ) echo "Please answer yes or no.";;
        esac
    done
    echo "and off we go!"
    

提交回复
热议问题