歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> linux命令之交互式輸入read

linux命令之交互式輸入read

日期:2017/3/1 16:26:32   编辑:關於Linux
linux命令之交互式輸入read read是一個重要的命令,用於從鍵盤或標准輸入中讀取輸入。 一般只有按回車鍵的時候才標志輸入完畢,但有些情況下沒法按回車鍵,read提供了一種不需要按回車鍵的方法。 1.-p “提示語句” 變量名 [wang@localhost 桌面]$ vim testcmd.sh #!/bin/bash read -p "Enter your name :" name1 name2 //name1前面要空格,可以賦值給多個變量 echo $name1 echo $name2 [wang@localhost 桌面]$ chmod +x testcmd.sh [wang@localhost 桌面]$ ./testcmd.sh Enter your name :william sam william sam [wang@localhost 桌面]$ ./testcmd.sh Enter your name :william sam linux //多余的輸入會賦值給最後一個變量 william sam linux 2.-n 輸入個數 當輸入字符數達到預定數目,則自動退出,不用按回車。 [wang@localhost 桌面]$ read -n 4 -p "Enter your name :" name;echo $name Enter your name :wangwang //一個wang是輸入的,另一個是echo $name。 3.-s 不回顯 用於輸入密碼,對於密碼的保護。 [wang@localhost 桌面]$ read -n 4 -s -p "Enter your name :" name;echo $name Enter your name :wang //這個是echo $name 4.-t 等待輸入的秒數 [wang@localhost 桌面]$ read -n 4 -t 2 -p "Enter your name :" name;echo $name Enter your name : //等2秒後 自動跳出了 或者寫個腳本: [wang@localhost 桌面]$ vim testcmd.sh #!/bin/bash if read -t 2 -p "Enter your name :" name then echo $name else echo "Timeout!" fi [wang@localhost 桌面]$ ./testcmd.sh Enter your name :Timeout! 5.-d 自定義定界符 輸入自定義的定界符,結束輸入。 [wang@localhost 桌面]$ read -d ":" -p "Enter your name :" name;echo $name Enter your name :name:name 6.從標准輸入中讀取 [wang@localhost 桌面]$ vim testcmd.sh #!/bin/bash count=1 cat test.c | while read line //從test.c讀取每一行並賦值給line變量 do echo "$count:$line" count=$[ count+1 ] done [wang@localhost 桌面]$ cat test.c #include <stdio.h> int main() { int a = 4; (++a) += a; printf("we are the best %d!\n",a); return 0; } [wang@localhost 桌面]$ ./testcmd.sh 1:#include <stdio.h> 2: 3:int main() 4:{ 5:int a = 4; 6:(++a) += a; 7:printf("we are the best %d!n",a); 8:return 0; 9:} 注意:上面的cat test.c 也可以換成ls ,ps,grep,find等等命令
Copyright © Linux教程網 All Rights Reserved