shell基礎知識6-在不按回車鍵的狀況下讀入N個字符

Bash命令 read 可以從鍵盤或標準輸入中讀取文本。咱們能夠使用 read 以交互的形式讀取用
戶輸入,不過 read 能作的可遠不止這些。編程語言的大多數輸入庫都是從鍵盤讀取輸入,當回
車鍵按下的時候,標誌着輸入完畢。但有時候是無法按回車鍵的,輸入結束與否是由讀取到的字
符數或某個特定字符來決定的。例如在交互式遊戲中,當按下 + 鍵時,小球就會向上移動。那麼
若每次都要按下 + 鍵,而後再按回車鍵來確認已經按過 + 鍵,這就顯然過低效了。node

read 命令提供了一種不須要按回車鍵就可以搞定這個任務的方法。編程

限制輸入的字符串

下面的語句從輸入中讀取10個字符並存入變量testRead編程語言

[root@dns-node2 ~]# read -n 10 testRead
1234567891[root@dns-node2 ~]# echo $testRead
1234567891
無回顯的方式讀取密碼
[root@dns-node2 ~]# read -s pwd
[root@dns-node2 ~]# echo $pwd
nihao
顯示提示信息以及限時讀取
[root@dns-node2 ~]# read -s -t 10 -p "Enter you pwd >" testIn
Enter you pwd >[root@dns-node2 ~]# echo $testIn
1234
自定義結束符
[root@dns-node2 ~]# read -d ";" -p "input your name" Testd
input your namehello
what's your name ;[root@dns-node2 ~]# echo $Testd
hello what's your name
相關文章
相關標籤/搜索