Linux基礎------Shell中的迴圈
Linux基礎------Shell中的迴圈
Linux shell程式設計中也存在著迴圈。迴圈分為兩種:一種是固定迴圈,另一種是不定迴圈。所謂固定迴圈和不定迴圈的定義是指在迴圈之前有沒有定義好迴圈的次數。
例如:for迴圈,給定迴圈最大的次數,這就是固定迴圈。例如:while迴圈,只有滿足指定的條件,迴圈才繼續,它沒有預先定義好的次數。
shell當中的迴圈命令有for,while和until。
一. for迴圈
命令的基本格式:
for var in list
do
your code
done
list引數,是指的迴圈中的一系列值。每一次迴圈,程式都會將list中的一個值賦給var變數。舉個例子:
#!/bin/bash
for test in a b c d
do
echo $test
done
輸出:a b c d
稍微複雜一點的例子,for也可以從命令中讀取值,
先儲存一個文字檔案,命名為test,裡面存放的資訊如下:
test1 test2
test3
test4
#!/bin/bash
file="test"
for line in `cat $file`
do
echo "This line of file is : $line"
done
輸出:
This line of file is:test1
This line of file is:test2
This line of file is:test3
This line of file is:test4
特別強調的是上面``,不是單引號' ',它是鍵盤左上角的反引號。在linux裡面,反引號之間的是可執行的命令。
關於for迴圈,裡面還有一個很重要的知識:IFS
IFS是一種被稱為內部欄位分割符的環境變數(internal field separator) 。IFS定義了shell中用作欄位分割的一系列字元。預設的字元為3種:空格,製表符,換行符。
shell在資料當中看到上述其中的任意一個字元,都會假定是開始了一個新的資料段,所以上面的指令碼輸出了4行資料。下面只要改一下IFS,輸出的內容就會發生改變:
#!/bin/bash
file="test"
IFS=$'\n'
for line in `cat $file`
do
echo "This line of file is : $line"
done
輸出:
This line of file is:test1 test2
This line of file is:test3
This line of file is:test4在for迴圈當中我們可能需要改一下IFS,但是在其他的地方我們需要預設的IFS,所以在程式中,應該這樣寫:
IFS.OLD=$IFS
IFS=$'\n'
your code
IFS=IFS.OLD
二. C風格的for迴圈
使用方法:for (( variable assignment; condition; iteration process )) ------>注意空格
do
your code
done
下面是一個例子:
#!bin/bash
for (( i=1; i <=3; i++))
do
echo "Number is $i"
done
輸出:
Number is 1
Number is 2
Number is 3
三. while迴圈
使用方法:while test command
do
your code
done
while允許定義多個測試命令(test command)。只有最後一個測試命令才來用來決定什麼時候退出迴圈。例子如下:
#!/bin/bash
var1=10
while echo $var1
[ $var1 -ge 0 ]
do
echo "This is inside the loop"
var1=$[ $var1 - 1 ]
done
輸出:
10
This is inside the loop
9
This is inside the loop8
This is inside the loop7
This is inside the loop6
This is inside the loop5
This is inside the loop4
This is inside the loop3
This is inside the loop2
This is inside the loop1
This is inside the loop-1
四. until迴圈
使用方法:until test command
do
your code
done
#!/bin/bash
until [ "$yn" != "y" -a "$yn" != "Y" ]
do
read -p "Please input y/Y to stop this program: " yn
done
echo "Loop End"
until和while迴圈正好相反,當滿足條件時,迴圈會自動退出。
四. 迴圈控制
break:跳出迴圈,預設的是跳出當前迴圈,如果break n,n就是指定的迴圈層數。例如break 2就是當前迴圈外的另一層。
continue:執行到contune時,跳出其他的linux命令,直接進行下一個迴圈。continue n與break n型別,也是指定迴圈的層數。