Bash is a shell for Linux and Unix operating systems. But bash also provides some basic programming environment acting like a Programming language. System administrators generally develops simple scripts and apps with bash and reads some input from shell interactively. In this tutorial we will look ho to read input from interactive bash console or terminal.
Bash是Linux和Unix操作系统的外壳。 但是bash还提供了一些基本的编程环境,就像编程语言一样。 系统管理员通常使用bash开发简单的脚本和应用,并以交互方式从shell中读取一些输入。 在本教程中,我们将查找如何从交互式bash控制台或终端读取输入。
通过使用读取 (By Using Read)
One way to get input from shell prompt is read. We use read and and question text to show and end of the line the variable name. This is the simplest form of getting an yes
, no
prompt from user.
从shell提示符获取输入的一种方法是读取。 我们使用阅读文本和问题文本显示变量名并在行尾显示。 这是从用户处获得yes
, no
提示的最简单形式。
$ read -p "Do you accept license?(y/n)" ans
Do you accept licence?(y/n)n
$ echo $ans
n
The other way with read is following printing text before and reading input after text with read.
与读取的另一种方式是继之前打印文本与文本阅读后读取输入。
$ echo "Do you accept license?(y/n)";read ans
Do you accept licence?(y/n)
y
通过使用选择 (By Using Select)
Another way to read input from bash shell is using conditional statement select
. This will read from console and set provided value to the ans
bash variable.
从bash shell读取输入的另一种方法是使用条件语句select
。 这将从控制台读取,并将提供的值设置为ans
bash变量。
echo "Do you accept license?"
select ans in "Yes" "No"; do
case $ans in
Yes ) break;;
No ) break;;
esac
done
通过使用马尾 (By Using Whiptail)
There is a library developed with ncurses which provides simple GUI for bash. Whiptail is used to read user input with a more beautiful way by providing graphical interface. In this example we simply provide --yesno
to the whiptail and it shows these predefined options. The result will be returned as Yes
or No
which is evaluated in a if
conditional statement.
有一个使用ncurses开发的库,它为bash提供简单的GUI 。 Whiptail用于通过提供图形界面以更优美的方式读取用户输入。 在此示例中,我们仅向--yesno
提供--yesno
,它显示了这些预定义的选项。 结果将以Yes
或No
形式返回,并在if
条件语句中进行评估。
$ if whiptail --yesno "Do you accept license?" 20 60 ;then echo Yes; else echo No; fi
Yes
$