循环与结构化命令

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  # 1,2,3
do
echo "$variable"
done
# 1
# 2
# 3
1
2
3
4
5
6
7
for variable in {1..3}  # 1,2,3
do
echo "$variable"
done
# 1
# 2
# 3
1
2
3
4
5
6
7
sum=0
for i in {1..10..2} # 1到10,步长为2
do
let "sum+=i"
done
echo "sum=$sum"
# 25
1
2
3
4
5
6
7
sum=0
for i in $(seq 1 2 10) # seq是一个命令,1到10,步长为2
do
let "sum+=i"
done
echo "sum=$sum"
# 25
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
# 1
# 2
# 3

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))
while [[ "$int" <= 3 ]] # 这两种都可以
do
echo "$int"
let "int++"
done
# 1
# 2
# 3
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

嵌套循环

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

循环控制符

  • break循环控制符

    1
    break
  • continue循环控制符

    1
    continue

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)  # 带列表的select
do
break
done
echo "the num is $num"
# 1) 1
# 2) 2
# 3) 3
# 4) 4
# #? 4
# the num is 4
1
2
3
4
5
6
7
8
9
10
11
12
13
selece num  # 不带列表的select
do
break
done
echo "the num is $num"
# ./xxx.sh 1 2 3 4

# 1) 1
# 2) 2
# 3) 3
# 4) 4
# #? 4
# the num is 4