Bootstrap

在Linux shell脚本中提示输入Yes/No/Cancel

在shell提示符下获取用户输入的一种广泛可用的方法是使用read命令。以下是一个演示:

while true; do
    read -p "Do you wish to install this program? " yn
    case $yn in
        [Yy]* ) make install; break;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac
done

另一种方法,是Bash的select命令。以下是使用select的相同示例:

echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
    case $yn in
        Yes ) make install; break;;
        No ) exit;;
    esac
done

使用select时,你不需要清理输入——它会显示可用的选择,你只需输入对应于你的选择的数字。它还会自动循环,因此如果输入无效,无需使用while true循环重试。

此外,一种使请求语言无关的方法。将我的第一个示例调整为更好地支持多种语言可能如下所示:

set -- $(locale LC_MESSAGES)
yesexpr="$1"; noexpr="$2"; yesword="$3"; noword="$4"

while true; do
    read -p "Install (${yesword} / ${noword})? " yn
    if [[ "$yn" =~ $yesexpr ]]; then make install; exit; fi
    if [[ "$yn" =~ $noexpr ]]; then exit; fi
    echo "Answer ${yesword} / ${noword}."
done
;