国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Linux系統中read 命令的使用

2019-11-14 08:50:19
字體:
來源:轉載
供稿:網友

read命令接受用戶輸入,并將輸入放入一個標準變量中。

基本用法如下:

$ cat test.sh#!/bin/bashecho -n "Enter you name: "read nameecho "Hello,$name!"$ ./test.shEnter you name: worldHello,world!這個例子中,我們首先輸出一句提示,然后利用read將用戶輸入讀取到name變量。使用-p選項,我們可以直接指定一個提示:
$ cat test.sh#!/bin/bashread -p "Enter you name:" nameecho "Hello,$name!"$ ./test.shEnter you name:worldHello,world!read命令也可以同時將用戶輸入讀入多個變量,變量之間用空格隔開。
$ cat test.sh#!/bin/bashread -p "Enter your name and age:" name ageecho "Hello,$name,your age is $age!"$ ./test.shEnter your name and age:tom 12Hello,tom,your age is 12!$ ./test.shEnter your name and age:tom 12 34Hello,tom,your age is 12 34!$ ./test.shEnter your name and age:tomHello,tom,your age is !在本例中,read命令一次讀入兩個變量的值,可以看出:如果用戶輸入大于兩個,則剩余的數據都將被賦值給第二個變量。如果輸入小于兩個,第二個變量的值為空。如果在使用read時沒有指定變量,則read命令會將接收到的數據放置在環境變量REPLY中:
$ cat test.sh#!/bin/bashecho "/$REPLY=$REPLY"read -p "Enter one  number:"echo "/$REPLY=$REPLY"$ ./test.sh$REPLY=Enter one  number:12$REPLY=12默認情況下read命令會一直等待用戶輸入,使用-t選項可以指定一個計時器,-t選項后跟等待輸入的秒數,當計數器停止時,read命令返回一個非0退出狀態。
$ cat test.sh#!/bin/bashif read -t 5 -p "Enter your name:" namethen     echo "Hello $name!"else    echo      echo "timeout!" fi$ ./test.sh Enter your name:worldHello world!$ ./test.sh Enter your name:timeout!使用-n選項可以設置read命令記錄指定個數的輸入字符,當輸入字符數目達到預定數目時,自動退出,并將輸入的數據賦值給變量。
$ cat test.sh #!/bin/bashread -n 1 -p "Enter y(yes) or n(no):" choiceecho echo "your choice is : $choice"$ ./test.sh Enter y(yes) or n(no):yyour choice is : y運行腳本后,只需輸入一個字母,read命令就自動退出,這個字母被傳給了變量choice。使用-s選項,能夠使用戶的輸入不顯示在屏幕上,最常用到這個選項的地方就是密碼的輸入。
$ cat test.sh#!/bin/bashread -s -p "Enter your passwd:" passwdecho echo "your passwd is : $passwd"$ ./test.shEnter your passwd:your passwd is : 123456read命令還可以讀取linux存儲在本地的文件,每調用一次read命令,都會從標準輸入中讀取一行文本,利用這個特性,我們可以將文件中的內容放到標準輸入流中,然后通過管道傳遞給read命令。
$ cat test.txt apple pen pearbananaorange$ cat test.sh#!/bin/bashcount=1cat test.txt | while read linedo     echo "Line $count: $line"    count=$[$count+1]doneecho "the file is read over"$ ./test.sh Line 1: appleLine 2: penLine 3: pearLine 4: bananaLine 5: orangethe file is read over讀到文件末尾,read命令以非零狀態碼退出,循環結束。


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 项城市| 河东区| 北海市| 南召县| 绥中县| 错那县| 兰西县| 九台市| 黄浦区| 思茅市| 桑植县| 天峨县| 讷河市| 弋阳县| 资阳市| 阿图什市| 清河县| 海阳市| 临泉县| 溧阳市| 拜城县| 堆龙德庆县| 聂拉木县| 明水县| 慈利县| 雅安市| 清水河县| 买车| 龙口市| 宁乡县| 黑水县| 万盛区| 攀枝花市| 凤山县| 延吉市| 滁州市| 读书| 大同县| 无棣县| 綦江县| 喀喇|