版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/twilight_karl/article/details/78373112
for 循环
语法一:
for 变量 in value1 value2 value3...
do
// do something
done
语法二 :
for (( 初始值;循环控制条件;变量变化 ))
do
// do something
done
案例一:
#!/bin/bash
for i in 1 2 3 4 5
do
echo $i
done
案例二:
#!/bin/bash
result=0
for ((i=1;i<=100;i=i+1))
do
result=$(($result+$i))
done
echo $result
案例三,批量添加用户:
#!/bin/bash
read -p "请输入用户名:" name
read -p "请输入创建用户的数量" number
read -p "请输入密码:" password
if [ -n "$name" -a -n "$number" -a -n "$password" ]
then
# 判断数量是否是数字
flag=`echo $number | sed "s/[0-9]//g" `
if [ -n flag ]
then
for (( i=1;i<=$number;i=i+1 ))
do
/usr/sbin/useradd $name$i
echo $passwd | /usr/bin/passwd --stdin $name$i
echo "成功添加用户$name$i,密码$passwd\n"
done
fi
else
echo "不能为空"
fi
案例四,批量删除用户:
#!/bin/bash
# 批量删除用户
read -p "请输入需要删除的用户名:" name
list=$(cat /etc/passwd | grep $name | cut -d ":" -f 1)
for i in $list
do
userdel $i
done
while 和 util
语法:
# 条件满足时执行循环
while [ 条件判断式 ]
do
// do something
done
# 条件满足时退出循环
until [ 条件判断式 ]
do
// do something
done
案例五:
[root@localhost sh]# vim while.sh
#!/bin/bash
# 测试while循环
i=1
s=0
while [ "$i" -le 100 ]
do
s=$(( $s+$i ))
i=$(( $i+1 ))
done
echo $s
案例六:
#!/bin/bash
i=1
s=0
until [ "$i" -gt 100 ]
do
s=$(( $s+$i ))
i=$(( $i+1 ))
done
echo $s