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

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

    Multiple choice version:

    ask () {                        # $1=question $2=options
        # set REPLY
        # options: x=..|y=..
        while $(true); do
            printf '%s [%s] ' "$1" "$2"
            stty cbreak
            REPLY=$(dd if=/dev/tty bs=1 count=1 2> /dev/null)
            stty -cbreak
            test "$REPLY" != "$(printf '\n')" && printf '\n'
            (
                IFS='|'
                for o in $2; do
                    if [ "$REPLY" = "${o%%=*}" ]; then
                        printf '\n'
                        break
                    fi
                done
            ) | grep ^ > /dev/null && return
        done
    }
    

    Example:

    $ ask 'continue?' 'y=yes|n=no|m=maybe'
    continue? [y=yes|n=no|m=maybe] g
    continue? [y=yes|n=no|m=maybe] k
    continue? [y=yes|n=no|m=maybe] y
    $
    

    It will set REPLY to y (inside the script).

提交回复
热议问题