Linux shell read 解析


read是一個重要的bash命令,它用於從鍵盤或標准輸入中讀取文本,我們可以用read以交互的方式讀取來自用戶的輸入,不過read能做的可遠不止這些,當從鍵盤讀取用戶輸入的時候,只有按下回車鍵才標志輸入結束,但是很多時候是沒辦法按回車鍵的,輸入結束與否是由某個特定字符決定的,例如:在一個游戲當中,當按下+鍵的時候,小球會向上移動。那么若是每次按+鍵再按回車鍵,未免太低效了。read命令提供了一種不需要按回車鍵就能搞定這個任務的方法。

1. 從下面的語句輸入中讀取n個字符並存入變量var中

1 [wandl@TestMachine2 shellScript]$ read -n 3 var
2 123[wandl@TestMachine2 shellScript]$ echo $var
3 123
4 #輸入第三個字符后直接結束輸入

2.用無回顯的方式讀取密碼

1 [wandl@TestMachine2 shellScript]$ read -s var
2 [wandl@TestMachine2 shellScript]$ echo $var
3 thisispassword
#在輸入字符時,不顯示

3.顯示提示信息

1 [wandl@TestMachine2 shellScript]$ read -p "Pls enter your name:" var
2 Pls enter your name:creazy
3 [wandl@TestMachine2 shellScript]$ echo $var
4 creazy

4.在特定時限內讀取輸入

1 [wandl@TestMachine2 shellScript]$ read -t 3 var
2 qw
3 [wandl@TestMachine2 shellScript]$ echo $var
4 qw
5 #在3秒鍾內輸入並且按回車鍵

5.用特定的定界符作為輸入行的結束

1 [wandl@TestMachine2 shellScript]$ read -d "q" var
2 weq[wandl@TestMachine2 shellScript]$ echo $var
3 we

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM