Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

linux - 如何在Linux Shell脚本中提示输入Yes / No / Cancel?(How do I prompt for Yes/No/Cancel input in a Linux shell script?)

I want to pause input in a shell script, and prompt the user for choices.

(我想在shell脚本中暂停输入,并提示用户选择。)

The standard 'Yes, No, or Cancel' type question.

(标准的“是,否或取消”类型的问题。)

How do I accomplish this in a typical bash prompt?

(如何在典型的bash提示中完成此操作?)

  ask by Myrddin Emrys translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest and most widely available method to get user input at a shell prompt is the read command.

(在shell提示符下获取用户输入的最简单,最广泛使用的方法是read命令。)

The best way to illustrate its use is a simple demonstration:

(演示其用法的最佳方法是一个简单的演示:)

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

Another method, pointed out by Steven Huwig , is Bash's select command.

(Steven Huwig 指出的另一种方法是Bash的select命令。)

Here is the same example using 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

With select you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice.

(使用select您不需要清理输入-它显示可用的选项,然后键入与您的选择相对应的数字。)

It also loops automatically, so there's no need for a while true loop to retry if they give invalid input.

(它还会自动循环,因此如果它们提供了无效的输入,则无需再进行一次while true循环重试。)

Also, Léa Gris demonstrated a way to make the request language agnostic in her answer .

(此外, LEA格里斯表现出一种方法,使在请求语言无关她的回答 。)

Adapting my first example to better serve multiple languages might look like this:

(修改我的第一个示例以更好地服务于多种语言可能看起来像这样:)

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

while true; do
    read -p "Install (${yesword} / ${noword})? " yn
    case $yn in
        ${yesptrn##^} ) make install; break;;
        ${noptrn##^} ) exit;;
        * ) echo "Answer ${yesword} / ${noword}.";;
    esac
done

Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.

(显然,这里没有翻译其他通信字符串(安装,回答),这需要通过更完整的翻译来解决,但是在许多情况下,即使是部分翻译也将有所帮助。)

Finally, please check out the excellent answer by F. Hauri .

(最后,请查看F. Hauri出色回答 。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...