从就键盘读取变量的值,通常用在shell脚本中与用户进行交互的场合。 该命令可以一次读取多个变量的值,变量和输入的值都需要使用空格隔开。 在read命令后面,如果没有指定变量名,读取的数据将被自动赋值给特定的变量REPLY
语法
read 变量名使用示例
[root@localhost shell]# read password admin123. [root@localhost shell]# echo $password admin123. [root@localhost shell]#语法
read 变量名1 变量名2使用示例
[root@localhost shell]# read first last abcde fghij [root@localhost shell]# echo $first abcde [root@localhost shell]# echo $last fghij [root@localhost shell]#参数"-s"可以将输入的内容隐藏起来,并赋值给指定的变量 语法
read -s 变量名使用示例 如,read -s password 可将输入的内容隐藏起来,并赋值给password。场景为输入用户密码
[root@localhost shell]# read -s password [root@localhost shell]# echo $password abcd123 [root@localhost shell]#参数 -p 可以增加让输入的提示信息 语法
read -p "input your password:" -s pwd使用示例
[root@localhost shell]# read -p "input your password:" -s pwd input your password: [root@localhost shell]# echo $pwd abcd123456 [root@localhost shell]#通过echo -n 的方式也能实现同样的提示效果 语法
echo -n "提示信息";read 变量名使用示例
[root@localhost shell]# echo -n "请输入:";read content 请输入:abc [root@localhost shell]# echo $content abc [root@localhost shell]#参数-t可以限制用户必须在多少秒之内输入,否则直接退出 语法
read -t 2 变量名使用示例
[root@localhost shell]# read -t 3 abc [root@localhost shell]# # 3秒未输入内容,程序自动退出参数 -n可以限制用户输入的内容的长度(单位是字符数量) 语法
read -n 长度值 变量名使用示例
[root@localhost shell]# read -n 3 length abc # 此处,输入3个字符后,自动退出 [root@localhost shell]# [root@localhost shell]# echo $length abc [root@localhost shell]# read -n 3 len 我是谁[ root@localhost shell]# [root@localhost shell]# echo $len 我是谁 [root@localhost shell]#由上面两例可看出,-n 后面跟的长度的单位是字符位
参数 -r 参数,允许让用户输入中的内容包括:空格、/、\、? 等特殊符号 语法
read -r 变量名使用示例
[root@localhost shell]# read -r strange |\d? abc [root@localhost shell]# echo $strange |\d? abc [root@localhost shell]#新建read_test.sh脚本,内容如下
#! /bin/bash read -p "请输入姓名:" NAME read -p "请输入性别:" GENDER read -p "请输入年龄:" AGE cat<<EOF ******************** 你的基本信息如下: 姓名:$NAME 性别:$GENDER 年龄:$AGE ******************** EOF执行脚本,结果如下: