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命令以非零狀態碼退出,循環結束。
新聞熱點
疑難解答