shell 之 read命令 读取变量值

1. read命令键盘读取变量的值

1.1 简介

  从就键盘读取变量的值,通常用在shell脚本中与用户进行交互的场合。
  该命令可以一次读取多个变量的值,变量和输入的值都需要使用空格隔开
  在read命令后面,如果没有指定变量名,读取的数据将被自动赋值给特定的变量REPLY

1.2 read常用方法及参数

参数意义/作用
-s隐藏用户键入的值
-p打印提示信息来提示用户输入正确的内容
-t设置用户输入的时间限制;超时则退出程序
-n限制用户输入内容的长度(单位是字符位)
-r允许用户输入特殊字符,如 空格、/、\、?等

1)从标准输入读取一行并赋值给变量password

语法

read 变量名

使用示例

[root@localhost shell]# read password
admin123.
[root@localhost shell]# echo $password
admin123.
[root@localhost shell]# 

2)读取多个值,从标准输入读取一行,直至遇到第一个空白或换行符。把用户键入的第一个词存到变量first中,把改行的剩余部分保存到变量last中

语法

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]# 

3)隐藏键入的值

参数"-s"可以将输入的内容隐藏起来,并赋值给指定的变量
语法

read -s 变量名

使用示例
如,read -s password 可将输入的内容隐藏起来,并赋值给password。场景为输入用户密码

[root@localhost shell]# read -s password
[root@localhost shell]# echo $password
abcd123
[root@localhost shell]# 

在这里插入图片描述

4)打印提示信息

参数 -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]# 

在这里插入图片描述

5)设置输入的时间限制

参数-t可以限制用户必须在多少秒之内输入,否则直接退出
语法

read -t 2 变量名

使用示例

[root@localhost shell]# read -t 3 abc
[root@localhost shell]# 						# 3秒未输入内容,程序自动退出

6)输入的长度限制

参数 -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 后面跟的长度的单位是字符位

7)输入特殊字符(不包括回车)

参数 -r 参数,允许让用户输入中的内容包括:空格/\? 等特殊符号
语法

read -r 变量名

使用示例

[root@localhost shell]# read -r strange
|\d? abc
[root@localhost shell]# echo $strange
|\d? abc
[root@localhost shell]# 

8)综合小练习

新建read_test.sh脚本,内容如下

#! /bin/bash
read -p "请输入姓名:" NAME
read -p "请输入性别:" GENDER
read -p "请输入年龄:" AGE

cat<<EOF
********************
你的基本信息如下:
姓名:$NAME
性别:$GENDER
年龄:$AGE
********************
EOF

执行脚本,结果如下:
在这里插入图片描述

  • 2
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值