循环与结构化命令
for循环
- 列表for循环
1 2 3 4 5 6
| for variable in {list} do command ... command done
|
1 2 3 4 5 6 7
| for variable in 1 2 3 do echo "$variable" done
|
1 2 3 4 5 6 7
| for variable in {1..3} do echo "$variable" done
|
1 2 3 4 5 6 7
| sum=0 for i in {1..10..2} do let "sum+=i" done echo "sum=$sum"
|
1 2 3 4 5 6 7
| sum=0 for i in $(seq 1 2 10) do let "sum+=i" done echo "sum=$sum"
|
1 2 3 4
| for file in $(ls) do echo "file:$file" done
|
1 2 3 4
| for file in $(*) do echo "file:$file" done
|
- 不带列表for循环:Shell会自动将
命令行键入的所有参数
依次组织成列表
1 2 3 4 5 6
| for variable do command ... command done
|
等价于
1 2 3 4 5 6
| for variable in "$@" do command ... command done
|
1 2 3 4
| for argument do echo "$argument" done
|
- 类C风格的for循环
1 2 3 4 5 6
| for((expr1; expr2; expr3)) do command ... command done
|
1 2 3 4 5 6 7
| for((integer=1; integer<=3; integer++)) do echo "$integer" done
|
while循环
1 2 3 4 5 6
| while expression do command ... command done
|
1 2 3 4 5 6 7 8 9 10
| int=1
while [[ "$int" <= 3 ]] do echo "$int" let "int++" done
|
1 2 3 4
| while [[ "$*" != "" ]]; do echo "$1" shift done
|
until循环
1 2 3 4 5 6
| until expression do command ... command done
|
1 2 3 4 5 6 7 8 9
| i=1 until [[ "$i" -gt 3 ]] do echo "$i" let "i++" done
|
嵌套循环
1 2 3 4 5 6 7 8 9 10 11 12
| for((i=1; i <= 9; i++)) do j=1 until [[ "$j" -gt "$i" ]] do let "n=i*j" echo -n "$i*$j=$n " let "j++" done echo "" done
|
循环控制符
select结构
1 2 3 4 5 6 7
| select variable in {list} do command ... command break done
|
1 2 3 4 5 6 7 8 9 10 11
| select num in $(seq 1 4) do break done echo "the num is $num"
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| selece num do break done echo "the num is $num"
|