8.4.1 跳出循环
要退出程序中的循环,可以使用break命令:
break
当执行到break时,控制会立刻转移到循环之外,然后继续往下执行。
如果要指定退出第几层内循环,可以在break后面加个整数n:
break n
8.4.2 跳过循环
跳过循环用
continue
和break类似,可以在continue 后面加个整数n,指定跳过最内侧的n个循环中的命令。
8.4.3 后台执行循环
要想循环在后台执行,只需要在done后面加一个&就可以了:
[root@centos7_c1 linux]# for file in mamo[1-4]
> do
> run $file
> done &
[1] 7769
8.4.4 循环上的I/O重定向
8.4.5 将数据导入及导出循环
命令输出可以导入循环(把该命令放在循环命令之前并以管道符号结尾),循环的输出也可以导入另一个命令。如下,for命令的输出被导入了wc:
[root@centos7_c1 linux]# for i in 1 2 3 4 5 6
> do
> echo $i
> done | wc -l
6
[root@centos7_c1 linux]#
8.4.6 单行循环
下面的循环:
[root@centos7_c1 linux]# for i in 1 2 3 4 5
> do
> echo $i
> done
1
2
3
4
5
可以写成:
[root@centos7_c1 linux]# for i in 1 2 3 4 5;do echo $i;done
1
2
3
4
5
注意分号添加的位置。