sh Bash:通用是/否提示功能(“问”)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sh Bash:通用是/否提示功能(“问”)相关的知识,希望对你有一定的参考价值。

# This is a general-purpose function to ask Yes/No questions in Bash, either
# with or without a default answer. It keeps repeating the question until it
# gets a valid answer.

ask() {
    # http://djm.me/ask
    while true; do

        if [ "${2:-}" = "Y" ]; then
            prompt="Y/n"
            default=Y
        elif [ "${2:-}" = "N" ]; then
            prompt="y/N"
            default=N
        else
            prompt="y/n"
            default=
        fi

        # Ask the question - use /dev/tty in case stdin is redirected from somewhere else
        read -p "$1 [$prompt] " REPLY </dev/tty

        # Default?
        if [ -z "$REPLY" ]; then
            REPLY=$default
        fi

        # Check if the reply is valid
        case "$REPLY" in
            Y*|y*) return 0 ;;
            N*|n*) return 1 ;;
        esac

    done
}


# EXAMPLE USAGE:

if ask "Do you want to do such-and-such?"; then
    echo "Yes"
else
    echo "No"
fi

# Default to Yes if the user presses enter without giving an answer:
if ask "Do you want to do such-and-such?" Y; then
    echo "Yes"
else
    echo "No"
fi

# Default to No if the user presses enter without giving an answer:
if ask "Do you want to do such-and-such?" N; then
    echo "Yes"
else
    echo "No"
fi

# Only do something if you say Yes
if ask "Do you want to do such-and-such?"; then
    said_yes
fi

# Only do something if you say No
if ! ask "Do you want to do such-and-such?"; then
    said_no
fi

# Or if you prefer the shorter version:
ask "Do you want to do such-and-such?" && said_yes

ask "Do you want to do such-and-such?" || said_no

以上是关于sh Bash:通用是/否提示功能(“问”)的主要内容,如果未能解决你的问题,请参考以下文章

sh Bash通用是/否提示功能(“询问”)

bash与sh的问题

sh Bash:if,then,else,echo:检查给定路径中是​​否存在任何文件

sh 缩短bash提示

sh bash严格模式和调试提示

sh git优化了bash提示符