Linux基础read命令

read命令简介

read命令用来倾听标准输入或文件输入,把信息存放到变量中。

read命令示例

-> cat test1
#!/bin/bash
# read 用来倾听用户的输入,将输入的内容保存到name变量中,使用echo显示输入的内容
echo -n "please input your name:"
read name
echo "welcome $name !!!"
# 赋予执行的权限
-> chmod u+x test1
# 执行test1
-> ./test1
please input your name:yangyun
welcome yangyun !!!
read命令的简略写法
-> cat test2
#!/bin/bash
read -p "please input your name:" name
echo "welcome $name !!!"
# 赋予执行的权限
-> chmod u+x test2
# 执行test2
-> ./test2
please input your name:yyy
welcome yyy !!!

## 如果不写变量的话,数据会存放到$REPLY的环境变量中
-> cat tset3
#!/bin/bash
read -p "please input your name and age:"
echo "Your name and age is $REPLY"
# 赋予执行的权限
-> chmod u+x test3
# 执行test3
-> ./test3
please input your name and age:yangyun 22
Your name and age is yangyun 22
read的等待时间
-> cat test4
#!/bin/bash
read -t 5 -p "please input your name within 5s:" name
echo "welcome $name !!!"
# 赋予执行的权限
-> chmod u+x test4
# 执行test4
-> ./test4
# 不输入,5s后输出结果
please input your name within 5s:welcome  !!!
# 输入,5后输入结果
please input your name within 5s:yang
welcome yang !!!
read输入密码
# 添加“-s”选项
-> cat test5
#!/bin/bash
read -s -p "please input your code:" passwd
echo "hi,your passwd is $passwd"
# 赋予执行的权限
-> chmod u+x test5
# 执行test5
-> ./test5
please input your code:
hi,your passwd is yyy
read读取内容
-> cat test6
1997
1998
1999

第一种使用-u

-> cat test7
#!/bin/bash
exec 3<test6
count=0
while read -u 3 var
do
 let count=$count+1
 echo "line $count:$var"
done
echo "finished"
echo "line no is $count"
exec 3<&-
# 赋予执行的权限
-> chmod u+x test7
# 执行test7
-> ./test7
line 1:1997
line 2:1998
line 3:1999
finished
line no is 3

第二种使用管道(“|”)

-> cat test8
#!/bin/bash
count=1
cat test6 | while read line
do
 echo "Line $count:$line"
 count=$[$count + 1]
done
echo "finished"
echo "Line no is $count"
# 赋予执行的权限
-> chmod u+x test8
# 执行test8
-> ./test8
Line 1:1997
Line 2:1998
Line 3:1999
finished
Line no is 1

第三种使用重定向

-> cat test9
#!/bin/bash
count=0
while read line
do
 count=$[$count + 1]
 echo "Line $count:$line"
done < test6
echo "finished"
echo "Line no is $count"
# 赋予执行的权限
-> chmod u+x test9
# 执行test9
-> ./test9
Line 1:1997
Line 2:1998
Line 3:1999
finished
Line no is 3
read命令的注意事项
  1. read命令在命令行输入变量时默认变量之间用空格进行分割;
  2. 如果输入的数据数量少于变量的个数,那么多余的变量不会获取到数据,那么变量值默认为空。
  3. 如果输入的数据数量多于变量的个数,那么超出的数据将都会赋值给最后一个变量。
  4. 反斜线""是续行符,在read命令中,不认为这是一行的结束,会继续读取下一行,直到遇到真正的换行符“\n”。
  5. 在read读取到的所有的数据中,所有的转义符表示的特殊含义都是起作用的。可以使用“-r“选项,这样任何符号都没有特殊身份了。”-r“选项不仅对读取的文件内容有效,而且对键盘的输入也是有效的。
  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值