Linux read 命令

Linux read 命令

Linux read命令用于从标准输入读取数值。

read 内部命令被用来从标准输入读取单行数据。这个命令可以用来读取键盘输入,当使用重定向的时候,可以读取文件中的一行数据。

语法

read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name ...]

参数说明:

  • -a 后跟一个变量,该变量会被认为是个数组,然后给其赋值,默认是以空格为分割符。
  • -d 后面跟一个标志符,其实只有其后的第一个字符有用,作为结束的标志。
  • -p 后面跟提示信息,即在输入前打印提示信息。
  • -e 在输入的时候可以使用命令补全功能。
  • -n 后跟一个数字,定义输入文本的长度,很实用。
  • -r 屏蔽,如果没有该选项,则作为一个转义字符,有的话 就是个正常的字符了。
  • -s 安静模式,在输入字符时不再屏幕上显示,例如login时输入密码。
  • -t 后面跟秒数,定义输入字符的等待时间。
  • -u 后面跟fd,从文件描述符中读入,该文件描述符可以是exec新开启的。

实例

1、简单读取

[root@iZ1la3d1xbmukrZ ~]# cat read1.sh
#!/bin/bash
echo "输入姓名:"
read input
echo "姓名:$input"
exit 0
[root@iZ1la3d1xbmukrZ ~]# sh read1.sh
输入姓名:
wgr
姓名:wgr
[root@iZ1la3d1xbmukrZ ~]# 

2、-p 参数,允许在 read 命令行中直接指定一个提示。

[root@iZ1la3d1xbmukrZ ~]# cat read2.sh
#!/bin/bash
read -p  "请输入姓名:" input
echo "姓名: $input"
exit 0
[root@iZ1la3d1xbmukrZ ~]# sh read2.sh
请输入姓名:wgr
姓名: wgr
[root@iZ1la3d1xbmukrZ ~]# 

3、-t 参数指定 read 命令等待输入的秒数,当计时满时,read命令返回一个非零退出状态。

[root@iZ1la3d1xbmukrZ ~]# cat read3.sh
#!/bin/bash
if read -t 5 -p "输入姓名" input
then
    echo "姓名:${input}"
else
    echo -e  "
输入超时"
fi

exit 0
[root@iZ1la3d1xbmukrZ ~]# sh read3.sh
输入姓名wgr
姓名:wgr
[root@iZ1la3d1xbmukrZ ~]# sh read3.sh
输入姓名
输入超时
[root@iZ1la3d1xbmukrZ ~]# 

4、除了输入时间计时,还可以使用 -n 参数设置 read 命令计数输入的字符。当输入的字符数目达到预定数目时,自动退出,并将输入的数据赋值给变量。

[root@iZ1la3d1xbmukrZ ~]# cat read4.sh
#!/bin/bash
read -n1 -p "Do you want to continue [Y/N]?" answer
case $answer in
Y | y)
     echo -e "
fine ,continue";;
N | n)
      echo -e "
ok,good bye";;
*)
     echo -e  "
error choice";;

esac
exit 0
[root@iZ1la3d1xbmukrZ ~]# sh read4.sh
Do you want to continue [Y/N]?Y
fine ,continue
[root@iZ1la3d1xbmukrZ ~]# 

5、-s 选项能够使 read 命令中输入的数据不显示在命令终端上(实际上,数据是显示的,只是 read 命令将文本颜色设置成与背景相同的颜色)。输入密码常用这个选项。

[root@iZ1la3d1xbmukrZ ~]# cat read5.sh
#!/bin/bash

read -s -p "请输入密码:" pass
echo -e "
您输入的密码是:$pass"
exit 0
[root@iZ1la3d1xbmukrZ ~]# sh read5.sh
请输入密码:
您输入的密码是:1234
[root@iZ1la3d1xbmukrZ ~]# 

6.读取文件

每次调用 read 命令都会读取文件中的 "一行" 文本。当文件没有可读的行时,read 命令将以非零状态退出。

通过什么样的方法将文件中的数据传给 read 呢?使用 cat 命令并通过管道将结果直接传送给包含 read 命令的 while 命令。

[root@iZ1la3d1xbmukrZ ~]# cat read6.sh
#!/bin/bash
count=1    # 赋值语句,不加空格
cat testfile | while read line      # cat 命令的输出作为read命令的输入,read读到>的值放在line中
do
   echo "Line $count:$line"
   count=$[ $count + 1 ]          # 注意中括号中的空格。
done
echo "finish"
exit 0
[root@iZ1la3d1xbmukrZ ~]# sh read6.sh
Line 1:HELLO LINUX!
Line 2:Linux is a free unix-type opterating system.
Line 3:This is a linux testfile!
Line 4:Linux test
finish
[root@iZ1la3d1xbmukrZ ~]# 

使用 -e 参数,以下实例输入字符 a 后按下 Tab 键就会输出相关的文件名(该目录存在的):

[root@iZ1la3d1xbmukrZ ~]#  read -e -p "输入文件名:" str
输入文件名:read
read1.sh  read2.sh  read3.sh  read4.sh  read5.sh  read6.sh
输入文件名:read
原文地址:https://www.cnblogs.com/dalianpai/p/12745844.html