1. 程式人生 > >Linux基礎read命令

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“選項不僅對讀取的檔案內容有效,而且對鍵盤的輸入也是有效的。