for循環
1.
列表for循環
for variable in {list} #有些像C++/CLR中的for each
do
...
done
如:
1.
[root@localhost tmp]# cat b.sh
#! /bin/bash
for i in 1 2 3 4 5 #1 2 3 4 5等價於{1..5}
do
echo $i
done
[root@localhost tmp]# ./b.sh
1
2
3
4
5
2.
[root@localhost tmp]# cat b.sh
#! /bin/bash
for i in $(seq 1 2 6) #從1增加到6,步幅爲2,相當於`seq 1 2 6`
do
echo $i
done
[root@localhost tmp]# ./b.sh
1
3
5
3.
[root@localhost tmp]# cat b.sh
#! /bin/bash
for i in $( ls ) #用命令ls的內容替換$( ls )
do
echo $i
done
[root@localhost tmp]# ./b.sh
1c
a
a1
a1~
...
4.
[root@localhost tmp]# cat b.sh
#! /bin/bash
for i in "$*" #把輸入的所有參數看做一個字符串整體
do
echo $i
done
[root@localhost tmp]# vim b.sh
[root@localhost tmp]# ./b.sh 1 2 3
1 2 3
[root@localhost tmp]# cat b.sh
#! /bin/bash
for i in "$@" #把輸入的參數分開看待
do
echo $i
done
[root@localhost tmp]# ./b.sh 1 2 3
1
2
3
2.
不帶列表的for循環
for variable
do
...
done
相當於
for variable in "$@"
do
...
done
3.
類C風格的for循環
for((expr1;expr2;expr3))
do
...
done
如:
for((i=1;i<=100;i+=2))
do
...
done
while循環
1.
[root@localhost tmp]# cat b1.sh
#! /bin/bash
echo "please enter start num:"
read i
echo ""$i"~10:"
while [ "$i" -ne 10 ]
do
echo $i
let "i++"
done
[root@localhost tmp]# ./b1.sh
please enter start num:
6
6~10:
6
7
8
9
2.類C語言模式
[root@localhost tmp]# cat b1.sh
#! /bin/bash
echo "please enter start num:"
read i
echo ""$i"~10:"
while ((i!=10)) #注意(()),和[ "$i" -ne 10 ]等價
do
echo $i
let "i++"
done
[root@localhost tmp]# ./b1.sh
please enter start num:
6
6~10:
6
7
8
9
3.
[root@localhost tmp]# cat b2.sh
#! /bin/bash
echo "you enter "$#" arguments" #$#爲參數的個數
while [ "$*" != "" ] #注意空格,等價於[ "$#" != 0 ](把"$#"當做字符串)和[ "$#" -ne 0 ](吧$#當做數字)
do
echo "$1"
shift #shift爲丟棄第一個參數($1),然後$1變爲$2,$2變爲$3以此類推
done
[root@localhost tmp]# ./b2.sh hello world !
you enter 3 arguments
hello
world
!
until循環
和while循環類似,只是while當條件爲真時繼續循環,而until當條件爲假時繼續循環
[root@localhost tmp]# cat b2.sh
#! /bin/bash
echo "you enter "$#" arguments"
until [ "$#" = 0 ]
do
echo "$1"
shift
done
[root@localhost tmp]# ./b2.sh hello world !
you enter 3 arguments
hello
world
!
控制字符
break 跳出最內層的循環
continue 跳出當前循環執行下一次的循環
select結構
select結構爲bash的擴展結構,類似於case,但交互性更好
例:
1.
[root@localhost tmp]# cat b3.sh
#! /bin/bash
echo "what's your favorite color?"
select color in "red" "blue" "green"
do
break
done
echo "you have selected $color"
[root@localhost tmp]# ./b3.sh
what's your favorite color?
1) red
2) blue
3) green
#? 2
you have selected blue
2.
[root@localhost tmp]# cat b3.sh
#! /bin/bash
echo "what's your favorite color?"
select color #相當於select color in "$@",類似於for color的情況
do
break
done
echo "you have selected $color"
[root@localhost tmp]# ./b3.sh red blue green
what's your favorite color?
1) red
2) blue
3) green
#? 2
you have selected blue