shell的循环结构及其流程控制

while(当型)循环结构

标准用法,当 condition 条件满足时执行循环体,否则退出循环

1
2
3
4
5
while [[ condition ]] ; do
# statements1
# statements2
# ...........
done

死循环,当触发某条件时退出循环

1
2
3
4
while : ; do
# statements1
# statements2 && break
done

将文件内容作为标准输入,遍历每一行进行循环体内的所有操作

1
2
3
4
5
while read col1 col2 ; do
# statements1
# statements2
# ...........
done < /path/to/filename

将进程替换的内容作为标准输入,遍历每一行进行循环体内的所有操作

1
2
3
4
5
while read col1 col2 ; do
# statements1
# statements2
# ...........
done < <(command)

until(直到型)循环结构

直到 condition 条件满足时退出循环,否则继续执行循环体

1
2
3
4
5
until [[ condition ]] ; do
# statements1
# statements2
# ...........
done

for循环结构

foreach型循环结构

1
2
3
4
5
6
for variable in WordList ; do
# statements1
# statements2
# ...........
done
# in WordList 可省略,省略时相当于 in "$@"

C语言型的循环结构

1
2
3
4
5
for (( exp1 ; exp2 ; exp3 )) ; do
# statements1
# statements2
# ...........
done

示例一

1
2
3
4
5
#!/bin/bash
for ((i=1;i<=100;i++));do
((sum=sum+i))
done
echo $sum

示例二

1
2
3
4
5
for i in {1..5} ; do
# statements1
# statements2
# …………..
done

示例三

1
2
3
4
5
for i in $(seq 5) ; do
# statements1
# statements2
# …………..
done

示例四

1
2
3
4
5
for i in 1 2 3 4 5 ; do
# statements1
# statements2
# …………..
done

循环控制

break 用于打断,跳出当前的整个循环

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[user1@study ~]$ cat test.sh
#!/bin/bash

for i in Tom 1 2 3 4 Jerry 5 6 7 8;do
if [[ "${i}" == "Jerry" ]];then
break
echo 'test'
else
echo ${i}
fi
done

[user1@study ~]$ bash test.sh
Tom
1
2
3
4
[user1@study ~]$

continue 会跳过本次循环,忽略剩余代码,进入循环的下一次迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[user1@study ~]$ cat test.sh  
#!/bin/bash

for i in Tom 1 2 3 4 Jerry 5 6 7 8;do
if [[ "${i}" == "Jerry" ]];then
continue
echo 'test'
else
echo ${i}
fi
done

[user1@study ~]$ bash test.sh
Tom
1
2
3
4
5
6
7
8
[user1@study ~]$

: 后面的同一行的语句不做任何操作,可以理解为将语句做了注释,需要注意 : 属于语句,而 # 只是注释符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[user1@study ~]$ cat test.sh 
#!/bin/bash

for i in Tom 1 2 3 4 Jerry 5 6 7 8;do
if [[ "${i}" == "Jerry" ]];then
: echo "yes"
echo 'test'
else
echo ${i}
fi
done

[user1@study ~]$ bash test.sh
Tom
1
2
3
4
test
5
6
7
8
[user1@study ~]$

在命令行执行 exit 会退出当前的 shell 终端

1
2
[user1@study ~]$ exit
logout

在脚本中不管在什么地方,执行语句遇到 exit 就会结束整个脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[user1@study ~]$ cat test.sh 
#!/bin/bash

for i in Tom 1 2 3 4 Jerry 5 6 7 8;do
if [[ "${i}" == "6" ]];then
exit
echo 'test'
else
echo ${i}
fi
done

[user1@study ~]$ bash test.sh
Tom
1
2
3
4
Jerry
5
[user1@study ~]$
有钱任性,请我吃包辣条
0%