经常我们会使用read命令来遍历读取文件

读取文件

读取文件的方式有很多种,下面介绍使用read命令进行读取,每次遍历文件的每一行,并获取每一行的内容,当文件再没有内容时,read命令会退出并返回非零状态码。

[root@localhost shell]# cat hello.txt 
huangbaokang
hello world
I love you

[root@localhost shell]# cat test.sh 
#!/bin/bash
count=1
cat hello.txt | while read line
do
	echo "Line $count:$line"
	count=$[$count+1]
done
echo "Finished!"
[root@localhost shell]# ./test.sh 
Line 1:huangbaokang
Line 2:hello world
Line 3:I love you
Finished!

给出提示(-p)

[root@localhost shell]# read -p "what's your name?" name
what's your name?huangbaokang
[root@localhost shell]# echo $name
huangbaokang

超时时间(-t)

如下3秒内没有输入,将自动退出。

[root@localhost shell]# read -t 3 -p "goodbye" name
goodbye[root@localhost shell]# 

不带变量,则报输入数据存储在REPLY环境变量

[root@localhost shell]# read
huangbaokang
[root@localhost shell]# echo $REPLY
huangbaokang

隐藏显示(-s)

所有的输入都不是要显示在控制台的,比如输入密码等。

[root@localhost shell]# read -s -p "please input your password:" password
please input your password:[root@localhost shell]# echo $password
huangbaokang