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 ~]# 
comments powered by Disqus