歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> read命令讀取用戶輸入

read命令讀取用戶輸入

日期:2017/3/1 9:25:36   编辑:Linux編程

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

Copyright © Linux教程網 All Rights Reserved