我如何提示在Linux shell脚本的输入? [英] How do I prompt for input in a Linux shell script?

查看:187
本文介绍了我如何提示在Linux shell脚本的输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要暂停在shell脚本的输入,并提示选择用户。该标准是,否或取消类型的问题。我如何做到这一点在一个典型的bash提示符?

I want to pause input in a shell script, and prompt the user for choices. The standard 'Yes, No, or Cancel' type question. How do I accomplish this in a typical bash prompt?

推荐答案

在shell提示下,以获取用户输入的最简单和最广泛使用的方法是的阅读'命令。为了说明其使用的最佳方法是一个简单的例子:

The simplest and most widely available method to get user input at a shell prompt is the 'read' command. 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

另一种方法,指出了由史蒂芬Huwig,是庆典的选择命令。下面是使用选择相同的例子:

Another method, pointed out by Steven Huwig, is bash's 'select' command. Here is the same example using 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 prompts you with your choices, and you type a number corresponding to the choice you want. Select also loops automatically... there's no need for a 'while true' loop to retry if they give invalid input.

另外,请在下方F. Hauri查看出色答卷

Also, please check out the excellent answer by F. Hauri below.

这篇关于我如何提示在Linux shell脚本的输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆