shell 之 read命令 读取变量值

您所在的位置:网站首页 如何在用shell脚本读取一个文件中指定的内容数据格式 shell 之 read命令 读取变量值

shell 之 read命令 读取变量值

#shell 之 read命令 读取变量值| 来源: 网络整理| 查看: 265

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


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3