Shell programming loop statement-for-while

Loop statement-for

Format 1

for 变量 in 数值 数值 数值 ..... #每次循环一次带入一个数值
 do
   执行语句
 done
 #常用使用循环

Format 2

for (( 变量=数值;变化变量值条件<=数值;变化变量=变量+数值)) #第一次循环变量的值带入,第二次循环变量的值就是变化变量的值但是这个是必须符合条件
do
  执行语句
done
#适合数学运算

#!/bin/bash

例子:openstack自动备份
source /root/admin
a=$(cat /root/openstack_list)
for i in $a ; do 
 openstack server backup create $i
done

例子:删除u开头的用户
#!/bin/bash

a=$(cat /etc/passwd | grep "/bin/bash" | cut -d : -f 1 | grep "^u")
for i in $a ; do
 userdel $i
done

while loop

As long as the condition is established, it will continue to loop. It is suitable for calculation. The loop body needs to judge the condition to fail to prevent the formation of an endless loop.

format

while [ 条件判断 ] ; do
 执行语句
done

例子:1+到100等于多少
#!/bin/bash
i=1
sun=2
while [ $i -le 100 ] ; do
 sun=$(($sun+$i))
 i=$(($i+1))
 echo "$sun"
done

until loop

In contrast to the while loop, as long as the condition is not satisfied it has been the cycle continues, the establishment of the end of the
format

until [ 条件判断 ] ; do
 执行语句
done

Three special control statements

  • exit []: End the script execution and return a value, the return value can be given to the administrator for judgment
    • The return value is checked by $?
  • break: exit the entire loop body
  • continue: end this cycle

Guess you like

Origin blog.csdn.net/yangshihuz/article/details/111483918