在本小节中,我们将学习如何从终端和脚本中读取(获取)用户输入。
要读取Bash用户输入,需要使用内置的Bash命令read。它用于从用户处获取输入并分配给变量。它仅从Bash shell中读取一行。以下是read命令的语法。
read
以下是从Bash脚本读取用户输入的示例:
示例1:
在此示例中,使用read命令从Bash脚本中读取了单个变量和多个变量。
#!/bin/bash
# Read the user input
echo "Enter the your name: "
read user_name
echo "Your name is $user_name"
echo
echo "Enter your age, phone and email: "
read age phone email
echo "your age is:$age, phone is:$phone, email: $email "
将上面示例代码保存到文件:read-input1.sh,执行后得到以下结果:
如果不使用read命令传递变量,将会发生什么?
如果我们不使用read命令传递变量,则可以在显示输入时传递一个名为REPLY的内置变量(应以$符号为前缀)。可以参考以下程序说明