在shell編程中經常用到循環,常用的循環有for和while循環兩種。while循環默認以行讀取文件,而for循環以空格讀取文件切分文件,本篇就結合現網的一些使用示例說說二者的用法和區別。
一、常用語法
1、for循環
for循環常用的語法結構有如下幾種:
for 變量 in seq字符串
for 變量 in `command` " "
for 變量 in "$@"或“$*”
for((賦值;條件;運算語句))
2、while循環
while循環常用的語法結構有如下幾種:
while [ $i -lt num ]while truewhile read a b c; do command done < filenamecat filename | while read a b c
二、行讀取示例
這里以常見的df獲取磁盤信息為例,了解下使用for和while的幾種循環方法處理時的區別。先看下我寫的腳本,內容如下:
#/bin/bash## author: yangbk## site: www.361way.com## mail: itybku@139.com## desc: test loop for in and whiledf -hl|awk 'int($5) >30 ' > testfileresult=`df -hl|awk 'int($5) >30 '`echo '******************* for testing *****************'for i in $result;doecho $idoneecho '******************* while echo test *************'echo $result | while read linedoecho $linedoneecho '****************** while testing ****************'df -hl|awk 'int($5) >30 '|while read linedoecho $IP `hostname` $linedoneecho '****************** while read file **************'while read linedoecho $IP `hostname` $linedone < testfile
上面的腳本執行時結果如下:
# sh forwhile.sh******************* for testing *****************/dev/sda39.5G5.7G3.4G64%//dev/sda239G19G18G52%/home/dev/sda69.5G7.1G2.0G78%/usr******************* while echo test *************/dev/sda3 9.5G 5.7G 3.4G 64% / /dev/sda2 39G 19G 18G 52% /home /dev/sda6 9.5G 7.1G 2.0G 78% /usr****************** while testing ****************localhost /dev/sda3 9.5G 5.7G 3.4G 64% /localhost /dev/sda2 39G 19G 18G 52% /homelocalhost /dev/sda6 9.5G 7.1G 2.0G 78% /usr****************** while read file **************localhost /dev/sda3 9.5G 5.7G 3.4G 64% /localhost /dev/sda2 39G 19G 18G 52% /homelocalhost /dev/sda6 9.5G 7.1G 2.0G 78% /usr
可以看到,只有后面兩種方法可以正常獲取到我們想要的數據,前面兩種方法在處理時和我們想要的結果都不一樣。此示例得出的結果為:
1、while循環: 以行讀取文件,默認分隔符是空格或者Tab;
2、for循環: 以空格讀取文件,也就是碰到空格,就開始執行循環體,所以需要以行讀取的話,就要把空格轉換成其他字符。
三、ssh連接與wait
這里還是以一個測試腳本為例:
#!/bin/bash## author: yangbk## site: www.361way.com## mail: itybku@139.com## desc: test wait and ssh when use for in and while# while loopecho -en "/t";datecat abc.txt|while read user ipdo{ssh -o ConnectTimeout=10 $user@$ip "hostname" < /dev/nullsleep 10s} &donewaitecho "This is while loop."echo -en "/t";datesleep 10secho -e "/n"# for loopecho -en "/t";datefor line in `cat abc.txt|sed -e 's/ /--/g'`do{user=`echo $line|awk -F '--' '{print $1}'`ip=`echo $line|awk -F '--' '{print $2}'`ssh -oConnectTimeout=10 $user@$ip "hostname"sleep 10s} &donewaitecho "This is for loop."echo -en "/t";date            
新聞熱點
疑難解答