Shell循环

好记性不如烂笔头,此文章记录循环的用法及方便后期查看回顾
脚本常用到的
常见的循环有3个:

  • while
  • for
  • until

while循环

格式: 当符合判断式的条件时就执行循环,直到不成立时才停止

while [ 判断式 ]
do
执行的程序  
done
举例:
[root@lUsmwg108555 ~]# cat while 
#!/bin/bash
while [ "$a" != "Yes" ]
do
	read -p "Please Enter Yes to stop the Program:" a
done
	echo "You are Success!"

[root@lUsmwg108555 ~]#
[root@lUsmwg108555 ~]# chmod +x while 
[root@lUsmwg108555 ~]# ./while 
Please Enter Yes to stop the Program:fsf
Please Enter Yes to stop the Program:yes
Please Enter Yes to stop the Program:Yes
You are Success!
[root@lUsmwg108555 ~]# 

until循环

格式:当不符合判断式的条件时就执行循环,直到成立时才停止(恰好与while相反)

until [ 判断式 ]
do
执行程序
done
举例:
[root@lUsmwg108555 ~]# cat until 
#!/bin/bash
until [ "$a" == "Yes" ]
do
    read -p "Please Enter Yes to Stop the Program:" a
done
    echo "You are Success!"
[root@lUsmwg108555 ~]# ./until 
Please Enter Yes to Stop the Program:
Please Enter Yes to Stop the Program:yes
Please Enter Yes to Stop the Program:Yes
You are Success!
[root@lUsmwg108555 ~]# 

for循环

for i in var 
do
执行程序
done

for ((i=1;i<=n;i++))
do
执行程序
done
举例1:
[root@lUsmwg108555 ~]# cat for 
#!/bin/bash

for i in {1..10}
do
	echo "$i times"
done
[root@lUsmwg108555 ~]# . /root/for 
1 times
2 times
3 times
4 times
5 times
6 times
7 times
8 times
9 times
10 times
[root@lUsmwg108555 ~]# 
举例2:
[root@lUsmwg108555 ~]# cat for 
#!/bin/bash

for ((i=1;i<=10;i++))
do
	echo "$i times"
done
[root@lUsmwg108555 ~]# . /root/for 
1 times
2 times
3 times
4 times
5 times
6 times
7 times
8 times
9 times
10 times
[root@lUsmwg108555 ~]# 

break和continue都是用来控制循环结构的,其主要作用是停止循环
前者是完全终止,跳出循环
后者则只是跳出当次的循环,开始下一次循环

举例:

break

[root@lUsmwg108555 ~]# cat break 
#!/bin/bash
for i in a b c d 
do 
echo -n "$i "
	for j in `seq 10`
	do
		if [ "$j" == 3 ];then
	    break
		fi
	echo -n " $j "
	done
	echo
done

[root@lUsmwg108555 ~]# . /root/break 
a  1  2 
b  1  2 
c  1  2 
d  1  2 
[root@lUsmwg108555 ~]# 

continue

[root@lUsmwg108555 ~]# cat break 
#!/bin/bash
for i in a b c d 
do 
echo -n "$i "
	for j in `seq 10`
	do
		if [ "$j" == 3 ];then
	    continue
		fi
	echo -n " $j "
	done
	echo
done

[root@lUsmwg108555 ~]# . /root/break 
a  1  2  4  5  6  7  8  9  10 
b  1  2  4  5  6  7  8  9  10 
c  1  2  4  5  6  7  8  9  10 
d  1  2  4  5  6  7  8  9  10 
[root@lUsmwg108555 ~]# 
comments powered by Disqus