read命令读取用户输入

read命令用于从终端或文件中读取用户输入,它读取整行输入,如果没有指定名称,读取的行被赋值给内部变量REPLY。
read命令常用选项:-a,-p,-s,-t,-n

1、REPLY变量

$read
hello
$echo $REPLY
hello

2、读入用户指定的变量

$read answer
hello
$echo $answer
hello

$read first second third
chen xiaopang panda
$echo $first $second $third
chen xiaopang panda

3、-p选项指定输入提示字符串

$read -p "Enter your name:" name
Enter your name:chenxiaopang
$echo $name
chenxiaopang

4、-a选项用于读入数组变量

$read -a friends
Tom Mike Jack
$echo ${friends[*]}
Tom Mike Jack

5、-t选项指定读入的时间限制

$read -t 5 choice //限定5秒钟内输入变量值,否则,不管用户是否输入,read命令返回非零值

6、-n选项指定读入的字符数目,当达到指定数目时,read命令返回

$read -n1 -p 'Enter your Choice (y/n): ' choice
$echo $choice
y

7、-s选项隐藏输入内容

$read -s name

8、从文件读入

cat test.txt | while read line
do

echo $line

done 

猜你喜欢

转载自www.linuxidc.com/Linux/2015-08/122471.htm