for

  1. for variable in {list}
  2. do
  3. startment1
  4. startment2
  5. done
  6. # 例子一
  7. #! /bin/bash
  8. for x in 1 2 3 4 5
  9. do
  10. echo ${x}
  11. done
  12. #例子二
  13. #! /bin/bash
  14. for x in {1..8}
  15. do
  16. echo ${x}
  17. done
  18. #例子三
  19. #! /bin/bash
  20. for x in {Mon Tue Wed Thu Fri Sat Sun} #大扩号可以省略
  21. do
  22. echo ${x}
  23. done
  24. #例子四,使用命令作为参数
  25. #! /bin/bash
  26. for x in $(ls) # 也可以直接使用ls或*号通配符,效果一致,注意*不能放到$()中
  27. do
  28. echo ${x}
  29. done
  30. #例子五
  31. #! /bin/bash
  32. for x in $@ #可以 $* 可以将命令执行入参作为循环对象
  33. do
  34. echo ${x}
  35. done
  1. for variable
  2. do
  3. startment1
  4. startment2
  5. done
  6. # 等价与下面语法
  7. for variable in $@ # 或者$*
  8. do
  9. startment1
  10. startment2
  11. done

条件真执行循环

  1. for ((expression1;expression2;expression3))
  2. do
  3. startment1
  4. ...
  5. done
  6. for ((i=0;i<10;i++))
  7. do
  8. echo ${i}
  9. done
  1. array=(1 2 3 4 5)
  2. for day in ${array[*]}
  3. do
  4. echo ${day}
  5. done

until 一直循环,知道条件成立退出循环

  1. until expression
  2. do
  3. startment1
  4. ...
  5. done
  6. i=0
  7. until [[ ${i} -gt 9 ]] # >
  8. do
  9. let "i+=1"
  10. echo ${i}
  11. done

批量添加用户和批量删除用户

  1. #! /bin/bash
  2. i=1
  3. until [ ${i} -eq 21 ] # =
  4. do
  5. useradd user${i} # mac没有这个命令
  6. echo "password" | passwd --stdin user${i} > /dev/null
  7. let "i++"
  8. done
  9. #! /bin/bash
  10. i=1
  11. until [ ${i} -eq 21 ] # =
  12. do
  13. userdel -r user${i} # mac也没有这个命令
  14. let "i++"
  15. done

while

  1. while expression
  2. do
  3. startment1
  4. ...
  5. done
  6. #! /bin/bash
  7. i=1
  8. while [ $i -lt 10 ] # <
  9. do
  10. echo $i
  11. let "i++"
  12. done
  13. # 例子二
  14. #! /bin/bash
  15. z=0
  16. for ((i=0;i<10;i++))
  17. do
  18. for ((j=0;j<10;j++))
  19. do
  20. num=$((j % 2))
  21. if [ $num -eq 0 ]
  22. then
  23. continue
  24. fi
  25. let "z=i+j"
  26. echo "z: ${z} ${j} ${num}"
  27. if [ $z -gt 10 ]
  28. then
  29. break 2
  30. fi
  31. done
  32. echo "i: $i"
  33. done