for循環的一般格式如下:
1 #!/bin/sh
2
3 for 變量 in 列表
4 do
5 command 1
6 command 2
7 command 1
8 ......... 9 command n 10 done
列表是一組值(數字、字符串等)組成的序列,每個值通過空格分隔。每循環一次,就將列表中的下一個值賦給變量。
列表也可以是一個文件:
in 列表是可選的,如果不用它,for 循環使用命令行的位置參數。
1 #!/bin/sh 2 3 for line in 1 2 3 4 5 6 7 4 do 5 echo "line is $line" 6 done
結果:
[root@localhost 1st]# sh test.sh
line is 1 line is 2 line is 3 line is 4 line is 5 line is 6 line is 7
下面用for循環讀一個文件:
查看文件內容
1 [root@localhost 1st]# cat test.txt
2 hello 3 wolrd 4 hello 5 shell 6 [root@localhost 1st]#
code:
1 #!/bin/sh
2
3 FILE=./test.txt
4
5 for line in $(<$FILE) 6 do 7 echo "line is: $line" 8 done
Results:
1 [root@localhost 1st]# sh xx.sh
2 line is: hello
3 line is: wolrd 4 line is: hello 5 line is: shell 6 [root@localhost 1st]#
while循環的一般格式如下:
1 while command
2 do
3
4 statement 5 6 done
code:
1 #!/bin/sh
2
3 i=0
4 sum=0
5 while [ $i -le 100 ]
6 do
7 sum=$(($sum + $i)) 8 i=$(($i + 1)) 9 done 10 echo "sum is $sum"
rusults:
1 [root@localhost 1st]# sh xx.sh 2 sum is 5050 3 [root@localhost 1st]#
if語句的一般格式如下:
1 if ....; then
2 ....
3 elif ....; then
4 .... 5 else 6 .... 7 fi
if 條件語句:
文件表達式:
1 [ -f "somefile" ] : 判斷是否是一個文件
2 [ -x "/bin/ls" ] : 判斷/bin/ls是否存在並有可執行權限 3 [ -n "$var" ] : 判斷$var變量是否有值 4 [ "$a" = "$b" ] : 判斷$a和$b是否相等 5 -r file 用戶可讀為真 6 -w file 用戶可寫為真 7 -x file 用戶可執行為真 8 -f file 文件為正規文件為真 9 -d file 文件為目錄為真 10 -c file 文件為字符特殊文件為真 11 -b file 文件為塊特殊文件為真 12 -s file 文件大小非0時為真 13 -t file 當文件描述符(默認為1)指定的設備為終端時為真
更短的if語句 # 一行 # Note: 當第一段是正確時執行第三段 # Note: 此處利用了邏輯運算符的短路規則 [[ $var == hello ]] && echo hi || echo bye [[ $var == hello ]] && { echo hi; echo there; } || echo bye
字符串表達式:
[string string_operator string]
這里string_operator可為如下幾種:
1 = 兩個字符串相等。
2 != 兩個字符串不等。 3 -z 空串。 4 -n 非空串
eg:
1 #!/bin/sh
2
3 NUMS="hello"
4 [ $NUMS = "hello" ]
5
6 echo $?
results:
1 [root@localhost 1st]# sh xx.sh 2 0
整數表達式:
1 -eq 數值相等。
2 -ne 數值不相等。 3 -gt 第一個數大於第二個數。 4 -lt 第一個數小於第二個數。 5 -le 第一個數小於等於第二個數。 6 -ge 第一個數大於等於第二個數。
Eg:
1 #!/bin/sh 2 3 NUMS=130 4 if [ $NUMS -eq "130" ]; then 5 6 echo "equal" 7 else 8 echo "not equal" 9 fi
results:
1 [root@localhost 1st]# sh xx.sh 2 equal