for
for variable in {list}
do
startment1
startment2
done
# 例子一
#! /bin/bash
for x in 1 2 3 4 5
do
echo ${x}
done
#例子二
#! /bin/bash
for x in {1..8}
do
echo ${x}
done
#例子三
#! /bin/bash
for x in {Mon Tue Wed Thu Fri Sat Sun} #大扩号可以省略
do
echo ${x}
done
#例子四,使用命令作为参数
#! /bin/bash
for x in $(ls) # 也可以直接使用ls或*号通配符,效果一致,注意*不能放到$()中
do
echo ${x}
done
#例子五
#! /bin/bash
for x in $@ #可以 $* 可以将命令执行入参作为循环对象
do
echo ${x}
done
for variable
do
startment1
startment2
done
# 等价与下面语法
for variable in $@ # 或者$*
do
startment1
startment2
done
条件真执行循环
for ((expression1;expression2;expression3))
do
startment1
...
done
for ((i=0;i<10;i++))
do
echo ${i}
done
array=(1 2 3 4 5)
for day in ${array[*]}
do
echo ${day}
done
until 一直循环,知道条件成立退出循环
until expression
do
startment1
...
done
i=0
until [[ ${i} -gt 9 ]] # >
do
let "i+=1"
echo ${i}
done
批量添加用户和批量删除用户
#! /bin/bash
i=1
until [ ${i} -eq 21 ] # =
do
useradd user${i} # mac没有这个命令
echo "password" | passwd --stdin user${i} > /dev/null
let "i++"
done
#! /bin/bash
i=1
until [ ${i} -eq 21 ] # =
do
userdel -r user${i} # mac也没有这个命令
let "i++"
done
while
while expression
do
startment1
...
done
#! /bin/bash
i=1
while [ $i -lt 10 ] # <
do
echo $i
let "i++"
done
# 例子二
#! /bin/bash
z=0
for ((i=0;i<10;i++))
do
for ((j=0;j<10;j++))
do
num=$((j % 2))
if [ $num -eq 0 ]
then
continue
fi
let "z=i+j"
echo "z: ${z} ${j} ${num}"
if [ $z -gt 10 ]
then
break 2
fi
done
echo "i: $i"
done