read命令接受用戶輸入,并將輸入放入一個(gè)標(biāo)準(zhǔn)變量中。
基本用法如下:
$ cat test.sh#!/bin/bashecho -n "Enter you name: "read nameecho "Hello,$name!"$ ./test.shEnter you name: worldHello,world!這個(gè)例子中,我們首先輸出一句提示,然后利用read將用戶輸入讀取到name變量。使用-p選項(xiàng),我們可以直接指定一個(gè)提示:$ cat test.sh#!/bin/bashread -p "Enter you name:" nameecho "Hello,$name!"$ ./test.shEnter you name:worldHello,world!read命令也可以同時(shí)將用戶輸入讀入多個(gè)變量,變量之間用空格隔開。$ 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命令一次讀入兩個(gè)變量的值,可以看出:如果用戶輸入大于兩個(gè),則剩余的數(shù)據(jù)都將被賦值給第二個(gè)變量。如果輸入小于兩個(gè),第二個(gè)變量的值為空。如果在使用read時(shí)沒有指定變量,則read命令會將接收到的數(shù)據(jù)放置在環(huán)境變量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默認(rèn)情況下read命令會一直等待用戶輸入,使用-t選項(xiàng)可以指定一個(gè)計(jì)時(shí)器,-t選項(xiàng)后跟等待輸入的秒數(shù),當(dāng)計(jì)數(shù)器停止時(shí),read命令返回一個(gè)非0退出狀態(tài)。$ 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選項(xiàng)可以設(shè)置read命令記錄指定個(gè)數(shù)的輸入字符,當(dāng)輸入字符數(shù)目達(dá)到預(yù)定數(shù)目時(shí),自動(dòng)退出,并將輸入的數(shù)據(jù)賦值給變量。$ 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運(yùn)行腳本后,只需輸入一個(gè)字母,read命令就自動(dòng)退出,這個(gè)字母被傳給了變量choice。使用-s選項(xiàng),能夠使用戶的輸入不顯示在屏幕上,最常用到這個(gè)選項(xiàng)的地方就是密碼的輸入。$ 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存儲在本地的文件,每調(diào)用一次read命令,都會從標(biāo)準(zhǔn)輸入中讀取一行文本,利用這個(gè)特性,我們可以將文件中的內(nèi)容放到標(biāo)準(zhǔn)輸入流中,然后通過管道傳遞給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命令以非零狀態(tài)碼退出,循環(huán)結(jié)束。
新聞熱點(diǎn)
疑難解答
圖片精選