read指令使用方法


 

read命令用於從標准輸入中讀取輸入單行,並將讀取的單行根據IFS變量分裂成多個字段,並將分割后的字段分別賦值給指定的變量列表var_name。第一個字段分配給第一個變量var_name1,第二個字段分配給第二個變量var_name2,依次到結束。如果指定的變量名少於字段數量,則多出的字段數量也同樣分配給最后一個var_name,如果指定的變量命令多於字段數量,則多出的變量賦值為空。

如果沒有指定任何var_name,則分割后的所有字段都存儲在特定變量REPLY中

常用參數
-p:給出提示符。默認不支持"\n"換行
-s:靜默模式。輸入的內容不會回顯在屏幕上
-t:給出超時時間,在達到超時時間時,read退出並返回錯誤
-n:限制讀取N個字符就自動結束讀取,如果沒有讀滿N個字符就按下回車或遇到換行符,則也會結束讀取
-N:嚴格要求讀滿N個字符才自動結束讀取,即使中途按下了回車或遇到了換行符也不結束。其中換行符或回車算一個字符
-a:將分裂后的字段依次存儲到指定的數組中,存儲的起始位置從數組的index=0開始
-p:給出提示符

簡短示例

#!/bin/bash
read -p "print a number: " num
if [ $num -eq 5 ]; then
echo "input right" && echo $num
else
echo "input error"
fi
exit
#執行
[root@localhost testsh]#./read.sh
print a number: 5
input right
如果沒有指定變量,read會把傳入的值傳給$REPLY,只要調用$REPLY就可以引用
#!/bin/bash

read -p "print a number: "
if [ $REPLY -eq 5 ]; then
echo "input right" && echo $REPLY
else
echo "input error"
fi
exit
-t:給出超時時間,在達到超時時間時,read退出並返回錯誤
#!/bin/bash
##
if read -t 5 -p "input a number: " num
then
echo "$num inputed"
else
echo "timeout"
fi
exit
#執行
[root@localhost testsh]#./timeout.sh
input a number: timeout
-n:限制讀取N個字符就自動結束讀取,如果沒有讀滿N個字符就按下回車或遇到換行符,則也會結束讀取
[root@localhost testsh]#read -n 5
12345[root@localhost testsh]#
[root@localhost testsh]#read -n 5
123
-a:將分裂后的字段依次存儲到指定的數組中,存儲的起始位置從數組的index=0開始
[root@localhost testsh]#read -a value
1 2 3 4
[root@localhost testsh]#echo ${value[0]}
1
[root@localhost testsh]#echo ${value[1]}
2
[root@localhost testsh]#echo ${value[2]}
3
[root@localhost testsh]#echo ${value[3]}
4
read讀取文件內容
#!/bin/bash
##
#read file ip.txt
cat /mnt/ip.txt | while read IP
do
echo "the ip : $IP"
done
echo "finsh"
exit
執行讀取ip.txt內容結果
the ip : 192.168.11.10
the ip : 192.168.11.11
the ip : 192.168.11.12
the ip : 192.168.11.13
the ip : 192.168.11.14
the ip : 192.168.11.15
the ip : 192.168.11.16
the ip : 192.168.11.17
the ip : 192.168.11.18
the ip : 192.168.11.19
finsh
或者使用for循環讀取
for IP in `cat /mnt/ip.txt`
do
echo $IP
done
read指令還可以將接收的值作為case語句判斷的條件值,使用如下
#!/bin/bash
read -t 30 -p "Do you want exit script[Y/N]?" char
case "$char" in
"Y" | "y")
echo "bye"
;;
"N" | "n")
echo "stay"
;;
*)
echo "output error,please input N,n/Y.y"
;;
esac

執行

[root@localhost testsh]#./bak.sh 
Do you want exit script[Y/N]?n
stay


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM