天天看点

Linux命令之read命令一、命令简介二、使用示例三、命令语法及参数说明

一、命令简介

  Linux read命令用于从标准输入读取数值。read 内部命令被用来从标准输入读取单行数据。这个命令可以用来读取键盘输入,当使用重定向的时候,可以读取文件中的一行数据。可以直接在命令行下直接,但常用于在shell脚本中输入自定义变量值。

二、使用示例

0、直接执行

[[email protected] scripts]# read

this is a test

1、-p参数给定输入提示

  • shell脚本

#!/bin/bash

read -p “输入姓名:” name

echo “你输入的姓名是:$name”

exit 0

  • 执行结果

[[email protected] scripts]# sh readshow.sh

输入姓名:吴先生

你输入的姓名是:吴先生

2、-s参数隐藏输入内容

  • shell脚本

#!/bin/bash

read -s -p “输入密码:” passwd

echo -e “\n你输入的密码是:$passwd”

exit 0

  • 执行结果

[[email protected] scripts]# sh readshow.sh

输入密码:

你输入的密码是:Test123

3、-t参数指定等待输入秒数

  • shell脚本

#!/bin/bash

if read -t 5 -p “输入姓名:” name

then

echo “你输入的姓名是 $name”

else

echo -e “\n抱歉,你输入超时了。”

fi

exit 0

  • 执行结果

[[email protected] scripts]# sh readshow.sh

输入姓名:

抱歉,你输入超时了。

4、-n参数控制输入字符,达到数目自动结束输入

  • shell脚本

#!/bin/bash

read -n1 -p “Do you want to continue [Y/N]?” answer

case $answer in

Y | y)

echo -e “\nfine ,continue”;;

N | n)

echo -e “\nok,good bye”;;

*)

echo -e “\nerror choice”;;

esac

exit 0

  • 执行结果

[[email protected] scripts]# sh readshow.sh

Do you want to continue [Y/N]?y

fine ,continue

[[email protected] scripts]# sh readshow.sh

Do you want to continue [Y/N]?N

ok,good bye

[[email protected] scripts]# sh readshow.sh

Do you want to continue [Y/N]?1

error choice

5、读取文件

  • shell脚本

[[email protected] scripts]# cat name.list

wuhs

sunru

bluesky

[[email protected] scripts]# cat readshow.sh

#!/bin/bash

\

count=1

cat name.list | while read line # cat命令的输出作为read命令的输入,read读到>的值放在line中

do

echo -e “Line c o u n t : count: count:line”

count=$[ $count + 1 ] # 注意中括号中的空格。

done

exit 0

  • 执行结果

[[email protected] scripts]# sh readshow.sh

Line 1:wuhs

Line 2:sunru

Line 3:bluesky

三、命令语法及参数说明

1、命令语法

用法:: read [-ers] [-a array] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name …]

2、参数说明

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

继续阅读