Linux shell编程学习笔记36:read命令

news2024/10/5 19:15:46

目录

  1. 0 前言
  2. 1 read命令的功能、格式、返回值和注意
    1. 1.1 命令功能
    2. 1.2 命令格式
    3. 1.3 返回值
    4. 1.4 注意事项
  3. 2 命令应用实例
    1. 2.1 一次读入多个变量值
    2. 2.2 不指定变量名
    3. 2.3 测试read命令的返回值
    4. 2.3 指定输入时限并进行相应处理
    5. 2.4 -t 指定结束符
    6. 2.5 -n 指定输入字符个数
    7. 2.6 -N 指定输入字符个数
    8. 2.7 -s不回显来自终端的输入
    9. 2.8 -e使用命令补全功能
    10. 2.9 -r 允许输入的值中包含的反斜杠\也作为值输出
    11. 2.10 -a 读取数组值
    12. 2.11 -u指定文件说明符

0 前言

在交互式编程中,有时我们需要用户先通过键盘来输入数据,然后程序根据用户输入的数据来做相应的处理。

在之前的学习中,我们已经使用read命令来读取用户通过键盘输入的数据,但对read命令没有做进一步的说明。

现在我们来研究一下read命令的详细用法。

1 read命令的功能、格式、返回值和注意

我们可以使用命令 help read  来查看seq命令的帮助信息:

purleEndurer @ bash ~ $ help read
read: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]
    Read a line from the standard input and split it into fields.
    
    Reads a single line from the standard input, or from file descriptor FD
    if the -u option is supplied.  The line is split into fields as with word
    splitting, and the first word is assigned to the first NAME, the second
    word to the second NAME, and so on, with any leftover words assigned to
    the last NAME.  Only the characters found in $IFS are recognized as word
    delimiters.
    
    If no NAMEs are supplied, the line read is stored in the REPLY variable.
    
    Options:
      -a array  assign the words read to sequential indices of the array
                variable ARRAY, starting at zero
      -d delim  continue until the first character of DELIM is read, rather
                than newline
      -e                use Readline to obtain the line in an interactive shell
      -i text   Use TEXT as the initial text for Readline
      -n nchars return after reading NCHARS characters rather than waiting
                for a newline, but honor a delimiter if fewer than NCHARS
                characters are read before the delimiter
      -N nchars return only after reading exactly NCHARS characters, unless
                EOF is encountered or read times out, ignoring any delimiter
      -p prompt output the string PROMPT without a trailing newline before
                attempting to read
      -r                do not allow backslashes to escape any characters
      -s                do not echo input coming from a terminal
      -t timeout        time out and return failure if a complete line of input is
                not read withint TIMEOUT seconds.  The value of the TMOUT
                variable is the default timeout.  TIMEOUT may be a
                fractional number.  If TIMEOUT is 0, read returns success only
                if input is available on the specified file descriptor.  The
                exit status is greater than 128 if the timeout is exceeded
      -u fd             read from file descriptor FD instead of the standard input
    
    Exit Status:
    The return code is zero, unless end-of-file is encountered, read times out,
    or an invalid file descriptor is supplied as the argument to -u.
readarray: readarray [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array]
    Read lines from a file into an array variable.
    
    A synonym for `mapfile'.
readonly: readonly [-aAf] [name[=value] ...] or readonly -p
    Mark shell variables as unchangeable.
    
    Mark each NAME as read-only; the values of these NAMEs may not be
    changed by subsequent assignment.  If VALUE is supplied, assign VALUE
    before marking as read-only.
    
    Options:
      -a        refer to indexed array variables
      -A        refer to associative array variables
      -f        refer to shell functions
      -p        display a list of all readonly variables and functions
    
    An argument of `--' disables further option processing.
    
    Exit Status:
    Returns success unless an invalid option is given or NAME is invalid.
purleEndurer @ bash ~ $ 

 1.1 命令功能

从标准输入或-u 选项指定的文件描述符读取一行。该行被拆分为多个字段,就像单词拆分一样,第一个单词分配给第一个 变量,第二个单词分配给第二个 变量,依此类推,任何剩余的单词都分配给最后一个 变量。如果未提供 变量名,则读取的行存储在 REPLY 变量中。

只有在 $IFS 中找到的字符才会被识别为单词分隔符。

1.2 命令格式

 read [-ers] [-a 索引数组名] [-d 结束符] [-i 文本] [-n 字符数] [-N 字符数] [-p 提示字符串] [-t 超时秒数] [-u 文件描述符] [变量名 ...]

  • 选项说明 
选项说明备注
-a 索引数组名将读取的单词从下标零开始分配给数组名指定的 索引数组,默认是以空格为分割符array
-d 结束符读取数据,直至结束符,而不是换行符delimiter
-e使用 Readline 在交互式 shell 中获取该行,在输入的时候可以使用命令补全功能
-i 文本使用指定的文本作为 Readline 的初始文本initialize
-n 字符数在读取指定的字符数后返回,除非遇到定界符、换行符或读取超时,定界符包括\t(tab键)。number
-N 字符数

在读取指定的字符数后返回,除非遇到 EOF 或读取超时

与 -n 不同的是,-N 会忽略任何定界符。

number
-p 提示字符串先输出提示字符串,再读取数据prompt
-r不允许反斜杠转义任何字符refuse
-s不回显来自终端的输入secrecy
-t 超时秒数

指定输入字符的等待时间。

如果在 超时秒数 内未读取完整的输入行,则超时并返回失败。
TMOUT变量的值是默认超时秒数。

超时秒数 可以是小数。
如果 超时秒数 为 0,则仅当指定的文件描述符上有可用的输入时,读取才会返回成功。
如果超过超时,则退出状态大于 128

timeout
-u 文件描述符从指定的文件描述符读入数据use

1.3 返回值

命令正常执行时返回值为零,

如果遇到文件末尾、读取超时或提供无效文件描述符作为 -u 的参数时,返回值不为零。

如果读取超时,返回值 将 大于 128。

1.4 注意事项

  • 变量名列表 应该放在 命令的最后。
  • 变量名之间以空格分隔。

2 命令应用实例

2.1 一次读入多个变量值

例:提示用户输入3个整数,作为a、c、c 三个变量的值

purpleEndurer @ bash ~ $ read -p "Enter there integers:" a  b c
Enter there integers:1 2 3
purpleEndurer @ bash ~ $ echo a=$a b=$b c=$c
a=1 b=2 c=3
purpleEndurer @ bash ~ $ read -p "Enter there integers:" a  b c
Enter there integers:1 2 3 4 5 6
purpleEndurer @ bash ~ $ echo a=$a b=$b c=$c
a=1 b=2 c=3 4 5 6
purpleEndurer @ bash ~ $ 

当我们输入1 2 3 这三个整数后,变量a的值为1,变量b的值为2,变量c的值为3。

当我们输入1 2 3 4 5 6 这六个整数后,由于我们只给了a、b、c三个变理名,所以变量a的值为1,变量b的值为2,而变量c的值为:3 4 5 6。

2.2 不指定变量名

例:提示用户输入3个整数,但没指定变量名

purpleEndurer @ bash ~ $ echo $REPLY

purpleEndurer @ bash ~ $ read -p "Enter there integers:"
Enter there integers:1 2 3
purpleEndurer @ bash ~ $ echo $REPLY 
1 2 3
purpleEndurer @ bash ~ $ 

由于我们没有指定变量名,所以输入的值1 2 3保存在变量REPLY中。

2.3 测试read命令的返回值

例:提示用户输入名字,输入时间限定为10秒钟

purpleEndurer @ bash ~ $ read -t 10 -p "Enter your name:"
Enter your name:pe
purpleEndurer @ bash ~ $ echo $?
0
purpleEndurer @ bash ~ $ read -t 10 -p "Enter your name:"
Enter your name:purpleEndurer @ bash ~ $ echo $?
142
purpleEndurer @ bash ~ $ read -t 10 -p "Enter your name:"
Enter your name:purpleEndurer @ bash ~ $ echo $?
1
purpleEndurer @ bash ~ $ read -t 10 -p "Enter your name:"
Enter your name:^C
purpleEndurer @ bash ~ $ echo $?
130
purpleEndurer @ bash ~ $ 

当我们在10秒钟内输入用户名pe并回车,read命令正常执行,返回值为0

当我们未在10秒钟内输入用户名,read命令返回值为142,大于128

当我们输入^D时,read命令返回值为1

当我们输入^C时,read命令返回值为130

2.3 指定输入时限并进行相应处理

例:编写一个脚本,提示用户在5秒钟内输入名字,如果用户输入名字,则对用户进行问候,否则提示用户没有输入名字。

脚本内容如下:

read  -t 5 -p "Enter you name in 5 seconds:" name # 提示用户在5秒钟内输入名字并保存在变量name中
if [ $? == 0 ]; then                              # 如果用户在5秒钟内输入了名字,那么read命令返回值为0
   echo Hello, $name.                             # 对用户进行问候
else
   echo -e "\nYou do not enter your name."        # 提示用户没有输入名字
fi

purpleEndurer @ bash ~ $ cp /dev/stdin a.sh
read  -t 5 -p "Enter you name in 5 seconds:" name
if [ $? == 0 ]; then
   echo Hello, $name.
else
   echo -e "\nYou do not enter your name."
fi

purpleEndurer @ bash ~ $ cat a.sh
read  -t 5 -p "Enter you name in 5 seconds:" name
if [ $? == 0 ]; then
   echo Hello, $name.
else
   echo -e "\nYou do not enter your name."
fi
purpleEndurer @ bash ~ $ . a.sh
Enter you name in 5 seconds:pe
Hello, pe.
purpleEndurer @ bash ~ $ . a.sh
Enter you name in 5 seconds:
You do not enter your name.
purpleEndurer @ bash ~ $ 

2.4 -t 指定结束符

例 读取用户输入值存入变量a,指定#作为结束符

purpleEndurer @ bash ~ $ read -d '#' a
ab#purpleEndurer @ bash ~ $ echo $a
ab
purpleEndurer @ bash ~ $ 

 

当我们输入ab#时,读取结束。变量a的值为ab。

2.5 -n 指定输入字符个数

例 读取5个字符,分别保存到变量a和b

purpleEndurer @ bash ~ $ read -n 5 a b
12345purpleEndurer @ bash ~ $ echo a=$a b=$b
a=12345 b=
purpleEndurer @ bash ~ $ read -n 5 a b
12 34purpleEndurer @ bash ~ $ echo a=$a b=$b
a=12 b=34
purpleEndurer @ bash ~ $ read -n 5 a b
1       234purpleEndurer @ bash ~ $ echo a=$a b=$b
a=1 b=234
purpleEndurer @ bash ~ $ read -n 5 a b
12
purpleEndurer @ bash ~ $ echo a=$a b=$b
a=12 b=
purpleEndurer @ bash ~ $ read -n 5 a b
123^C
purpleEndurer @ bash ~ $ echo a=$a b=$b
a=12 b=
purpleEndurer @ bash ~ $ 

当我们输入12345时,变量a的值为12345,变量b值为空

当我们输入12空格34时,变量a的值为12,变量b值为34

当我们输入1[Tab]234时,变量a的值为1,变量b值为234

当我们输入12回车时,变量a的值为12,变量b值为空

当我们输入123^C时,read命令被终止了,所以变量a的值没有变化,仍为12,变量b值没有变化,仍为空

2.6 -N 指定输入字符个数

例 读取5个字符,分别保存到变量a和b

purpleEndurer @ bash ~ $ read -N 5 a b
12      34purpleEndurer @ bash ~ $ echo a=$a b=$b
a=12 34 b=
purpleEndurer @ bash ~ $ read -N 5 a b
12 34purpleEndurer @ bash ~ $ echo a=$a b=$b
a=12 34 b=
purpleEndurer @ bash ~ $ read -d '#' -N 5 a b
12#34purpleEndurer @ bash ~ $ echo a=$a b=$b
a=12#34 b=
purpleEndurer @ bash ~ $ 

 

 当我们输入12[Tab]34时,变量a的值为12    34,变量b值为空

当我们输入12空格34时,变量a的值为12 34,变量b值为空

即使我们用-t '#' 选项指定#作为结束符,输入12#34,结果变量a的值为12#34,变量b值为空 

  • 看来使用-N选项后,空格或[Tab]不再作为字符串值的分隔符,-t选项也不起作用,这样只能将读取值存到第1个变量中了。

2.7 -s不回显来自终端的输入

例:提示用户输入密码,输入时不回显,输入完成后再显示用户输入的密码。

purpleEndurer @ bash ~ $ read -s -p "Enter your password:" p
Enter your password:purpleEndurer @ bash ~ $ echo Your password is $p
Your password is abcd
purpleEndurer @ bash ~ $ 

当用户输入密码abcd时并不回显,按回车键后,才显示用户输入的密码是abcd。

2.8 -e使用命令补全功能

purpleEndurer @ bash ~ $ ls
Code
purpleEndurer @ bash ~ $ read -e a
Code/
purpleEndurer @ bash ~ $ echo $a
Code/
purpleEndurer @ bash ~ $ 

我们先用ls命令查看当前目录内容,存在一个名Code的文件或文件夹

然后我们用命令 read -e a 来读取输入存到变量a

在我们输入大写字符C后按Tab键启用命令补全功能,输入行的内容就变为Code/,按下回车键。

再用echo $a 查看变量a的值为Code/

2.9 -r 允许输入的值中包含的反斜杠\也作为值输出

purpleEndurer @ bash ~/Code $ read a
//\c
purpleEndurer @ bash ~/Code $ echo $a
//c
purpleEndurer @ bash ~/Code $ read -r a
//\c
purpleEndurer @ bash ~/Code $ echo $a
//\c
purpleEndurer @ bash ~/Code $ 

对于命令 read a,输入   //\c,存储到变量a的值为 //C,不包含反斜杠\。

对于命令 rread -r a,输入   //\c,存储到变量a的值为 //\C,包含反斜杠\。

2.10 -a 读取数组值

数组是最常用的一种数据结构,在之前的

Linux shell编程学习笔记15:定义数组、获取数组元素值和长度、数组拼接或合并_linux获取数组长度-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/Purpleendurer/article/details/134009982

Linux shell编程学习笔记16:bash中的关联数组-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/Purpleendurer/article/details/134053506中我们学习了Lininux Shell编程中的数组的定义和赋值的方法,其中对数组元素的赋值方法 ,我们主要介绍了在定义数组时同时进行初始化和定义数组后用赋值语句来赋值两种方法。

现在我们也可以用read命令来将用户输入的值存储到数组

例:从键盘读取输入存入数组a

purpleEndurer @ bash ~/Code $ echo ${a[*]}
1 2 3
purpleEndurer @ bash ~/Code $ read -a a
1 2 3
purpleEndurer @ bash ~/Code $ echo ${a[*]}
1 2 3
purpleEndurer @ bash ~/Code $ echo ${a[0]}
1
purpleEndurer @ bash ~/Code $ 

可惜的是,read命令不能将用户输入存储到关联数组

purpleEndurer @ bash ~/Code $ declare -A A
purpleEndurer @ bash ~/Code $ read -a A
a b c
bash: read: A: cannot convert associative to indexed array
purpleEndurer @ bash ~/Code $ 

我们先用命令 声明一个关联数组A

然后用命令 来读取用户输入存储到关联数组A,但是出错了:bash: read: A: cannot convert associative to indexed array

2.11 -u指定文件说明符

例:将文件a.txt和b.txt的内容逐行拼接显示。

purpleEndurer @ bash ~ $ cp /dev/stdin a.txt
111
222
333
444

purpleEndurer @ bash ~ $ cp /dev/stdin b.txt
aaa
bbb
ccc
ddd
eee

purpleEndurer @ bash ~ $ while read -u3 i && read -u4 j;do echo $i $j; done 3<a.txt 4<b.txt
111 aaa
222 bbb
333 ccc
444 ddd
purpleEndurer @ bash ~ $ 

如果我们希望在每一行前显示行号,那么我们可以增加一个变量n用来记录当前行数:

purpleEndurer @ bash ~ $ n=1;while read -u3 i && read -u4 j;do echo Line $n:  $i $j;n=$[ $n + 1 ];  done 3<a.txt 4<b.txt
Line 1: 111 aaa
Line 2: 222 bbb
Line 3: 333 ccc
Line 4: 444 ddd
purpleEndurer @ bash ~ $ 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1320347.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

分类预测 | Matlab实现AOA-SVM算术优化支持向量机的数据分类预测【23年新算法】

分类预测 | Matlab实现AOA-SVM算术优化支持向量机的数据分类预测【23年新算法】 目录 分类预测 | Matlab实现AOA-SVM算术优化支持向量机的数据分类预测【23年新算法】分类效果基本描述程序设计参考资料 分类效果 基本描述 1.Matlab实现AOA-SVM算术优化支持向量机的数据分类预测…

css的filter全属性介绍

原图&#xff1a; 模糊&#xff08;blur&#xff09; 单位可为px或rem&#xff0c;值越大&#xff0c;越模糊 filter:blur(3px) filter:blur(0.3rem) 亮度(brightness) 值可为数字或百分数&#xff0c;小于1时&#xff0c;亮度更暗&#xff1b;等于1时&#xff0c;无变化&am…

微信支付怎么申请0.2费率

作为移动支付的主流方式&#xff0c;微信收款和支付宝为商家带来了便利的同时&#xff0c;每笔交易都要收取的0.6&#xff05;收款手续费也成为商家的负担。现在使用现金支付的人少之又少&#xff0c;为了给顾客带来便捷的购物体验&#xff0c;所以即便是要付出手续费&#xff…

十四、YARN核心架构

1、目标 &#xff08;1&#xff09;掌握YARN的运行角色和角色之间的关系 &#xff08;2&#xff09;理解使用容器做资源分配和隔离 2、核心架构 &#xff08;1&#xff09;和HDFS架构的对比 HDFS架构&#xff1a; YARN架构&#xff1a;&#xff08;主从模式&#xff09; &…

visual stdio code运行vue3

npm init vuelatest 该命令初始化vue项目 使用visual stdio code创建vue项目 ,这边是vue-project文件夹 vs code打开项目 vscode操作vue项目 vscode操作vue项目

【Leetcode】旋转矩阵

题目链接&#xff1a;https://leetcode.cn/problems/rotate-matrix-lcci/description/ 题目描述 给你一幅由 N N 矩阵表示的图像&#xff0c;其中每个像素的大小为 4 字节。请你设计一种算法&#xff0c;将图像旋转 90 度。 不占用额外内存空间能否做到&#xff1f; 示例 …

找出一个二维数组中的鞍点

找出一个二维数组中的鞍点&#xff0c;即该位置上的元素在该行上的最大、在该列上最小。也有可能没有鞍点。 #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> int main() {int a[10][10] { 0 };int n 0, m 0;int i 0, j 0;printf("请输入这个数组有n行m列…

算法学习——栈与队列

栈与队列 栈与队列理论基础用栈实现队列思路代码 用队列实现栈思路代码 删除字符串中的所有相邻重复项思路代码 有效的括号思路代码 逆波兰表达式求值思路代码 滑动窗口最大值思路代码未完待续 前 K 个高频元素思路代码拓展 总结栈在系统中的应用括号匹配问题字符串去重问题逆波…

FPGA时序分析与时序约束(二)——时钟约束

目录 一、时序约束的步骤 二、时序网表和路径 2.1 时序网表 2.2 时序路径 三、时序约束的方式 三、时钟约束 3.1 主时钟约束 3.2 虚拟时钟约束 3.3 衍生时钟约束 3.4 时钟组约束 3.5 时钟特性约束 3.6 时钟延时约束 一、时序约束的步骤 上一章了解了时序分析和约束…

LinuxCNC的使用

先进行程序设置 点击“开始”,选择“创建新的配置” 设置好机床名称和单位 关键是需要设置并口地址 查看并口使用命令:lscpi -v 将使用的并口填入: 这里是设置页面

Vue 自定义搜索输入框SearchInput

效果如下&#xff1a; 组件代码 <template><div class"search-input flex flex-space-between flex-center-cz"><input type"text" v-model"value" :ref"inpuName" :placeholder"placeholder" keyup.enter&…

6.s081操作系统Lab4: trap

文章目录 chapter 4概览4.1 CPU trap流程使用寄存器如果cpu想处理1个trap 4.2 用户态引发的trap4.2.1 uservec4.2.2 usertrap4.2.3 usertrapret和userretusertrapretuserret Lab4Backtrace (moderate)Alarm (hard) chapter 4 概览 trap的场景&#xff1a;系统调用&#xff0c…

Unity3D拆分模型动画展示

系列文章目录 Unity工具 文章目录 系列文章目录前言一、模型拆分功能1-1、首先先搭建一个简单的场景1-2、导入DoTween插件1-3、代码实现1-4、效果展示&#xff08;一个一个拆分的&#xff09; 二、对称模型拆分2-1、规则的&#xff0c;镜像的&#xff0c;对称的都可以使用2-2、…

gitee提交代码步骤介绍(含git环境搭建)

1、gitee官网地址 https://gitee.com; 2、Windows中安装git环境 参考博客&#xff1a;《Windows中安装Git软件和TortoiseGit软件》&#xff1b; 3、设置用户名和密码 这里的用户名和密码就是登录gitee网站的用户名和密码如果设置错误&#xff0c;可以在Windows系统的“凭据管理…

八股文打卡day3——计算机网络(3)

面试题&#xff1a;请讲一下四次挥手的过程&#xff1f; 1.客户端发送FIN数据包给服务器&#xff0c;表示客户端不再发送数据给服务器&#xff0c;想要断开这个方向的连接。 2.服务器收到客户端的FIN包之后&#xff0c;发送ACK包给客户端&#xff0c;对收到的FIN包进行收到确认…

你也是爬虫高手?毫秒级抢票,光速入监狱

文章目录 前言案情介绍法院观点判决情况判决文书案例分析 关于Python技术储备一、Python所有方向的学习路线二、Python基础学习视频三、精品Python学习书籍四、Python工具包项目源码合集①Python工具包②Python实战案例③Python小游戏源码五、面试资料六、Python兼职渠道 前言 …

C++ 开发中为什么要使用继承

为何继承 实验介绍 继承是 C++ 中的特性之一,使用继承能够有效减轻工作量,使得开发更加高效。 知识点 什么是继承为何继承继承的内容权限关键字什么是继承 生活中继承是指孩子继承父亲的财产等。C++ 使用了这一思想,却又与生活中的继承不一样。 在使用继承时,派生类是…

cesium学习笔记(问题记录)——(三)

一、根据点跟角度计算另一点坐标&#xff08;三维球体&#xff09; export const getAnotherPoint (lon: number, lat: number, angle: number, distance: number) > {// WGS84坐标系var a 6378137; // 赤道半径var b 6356752.3142; // 短半径var f 1 / 298.257223563;…

valgrind定位C++线程/内存等错误

Valgrind 是一套 Linux 下&#xff0c;开放源代码&#xff08;GPL V2&#xff09;的仿真调试工具的集合。 Valgrind 由内核&#xff08;core&#xff09;以及基于内核的其他调试工具组成。内核类似于一个框架&#xff08;framework&#xff09;&#xff0c;它模拟了一个 CPU 环…

【漏洞复现】CVE-2023-47261 Dokmee ECM信息泄露致远程命令执行

漏洞描述 Dokmee ECM是一款国外企业内容管理 (ECM) 软件。每个公司的办公室每个角落都存放着文档、记录和档案。Dokmee 一系列解决方案可以帮助您高效地组织、保护和管理这些文件。支持的文件:PDF、TIFF、Word、Excel、Auto-CAD 绘图、电子邮件等。Dokmee 可以帮助您立即实现…