Linux read的用法
作者:子非木
鏈接:https://www.cnblogs.com/wangtao1993/p/6136169.html
1、read基本讀取
#!/bin/bash #testing the read command echo "Enter you name:" #echo -n 讓用戶直接在後面輸入 read #輸入的多個文本將保存在一個變數中 echo "Hello $name 1
2
3
4
5
6
執行:
read name to program# ./
Enter you
Hello wangtao, welcome
2、read -p (
直接在read命令行指定提示符
)#!/bin/bash #testing the read -p option 1
2
3
read
-p"Please enter your age: "
age4 days=$[
$age
* 365 ]5
echo
"That makes you over
$days
days old!"執行:
# ./age.sh Please 23
That makes you over
8395
days old!3、read -p (指定多個變數)
#!/bin/bash # entering multiple variables read "Enter your name:" echo "Checking data for $last $first 1
2
3
4
5
"
執行:
# ./read1.sh for
Enter your name: a b
Checking data
4、read 命令中不指定變數
,那麼read命名將它收到的任何數據都放在特殊環境變數REPLY中#!/bin/bash # testing the REPLY environment variable read "Enter a number: " 1
2
3
4
5 factorial=1
6
for
(( count=1; count<=$REPLY
; count++ ))7
do
8 factorial=$[
$factorial
*$count
]#等號兩端不要有空格
9
done
10
echo
"The factorial of
$REPLY
is$factorial
"
執行:
6 of 6 is 720./read2.sh
Enter a number:
The factorial
5、超時, 等待輸入的秒數(read -t)
#!/bin/bash 1
2
# timing the data entry
3
4
if
read
-t 5 -p"Please enter your name: "
name#記得加-p參數, 直接在read命令行指定提示符
5
then
6
echo
"Hello
$name
, welcome to my script"7
else
8
echo
9
echo
"Sorry, too slow!"
10
fi
執行:
# ./read3.sh Please
Sorry, too slow!
# ./read3.sh Please
Hello wang, welcome to my script
5、read命令對輸入的字元判斷
#!/bin/bash # getting just one character of input read "Do you want to continue [Y/N]? " case $answer in echo echo "fine, continue on..." echo echo "OK, goodbye" exit esac 1
2
3
4
5
6 Y | y)
7
8 N | n)
9
10
11
執行:
# ./read4.sh Do to continue continue on
fine,
./read4.sh
Do
you wantto
continue
[Y/N]? nOK, goodbye
6、隱藏方式讀取(
read -s
)#!/bin/bash # hiding input data from the monitor read "Enter your passwd: " #-s 參數使得read讀入的字元隱藏 echo echo "Is your passwd readlly $pass 1
2
3
4
5
6
~
執行:
# ./read5.sh Enter 206
Is your passwd readlly osfile@
7、從文本中讀取
#!/bin/bash # reading data from a file test while read do echo "Line $count $line 1
2
3
4 count=1
5 cat
6
7
8 count=$[
$count
+ 1 ]9
done
10
echo
"Finished processing the file"
執行:
1 2 is this is 3 ./read6.sh
Line
Line
Line
Finished processing the file
●編號682,輸入編號直達本文
●輸入m獲取文章
目錄
推薦↓↓↓
運維
更多推薦
《
25個技術類公眾微信
》
涵蓋:程序人生、演算法與數據結構、黑客技術與網路安全、大數據技術、前端開發、Java、Python、Web開發、安卓開發、iOS開發、C/C++、.NET、Linux、資料庫、運維等。
※Linux中如何查詢埠被佔用的情況
※138 條 Vim 命令、操作、快捷鍵全集
TAG:Linux學習 |