2, 判断循环
a)whlie 语句
使用 while 循环结构, 当条件满足时反复执行指定动作, 否则终止
语法:
while 条件
do
动作1
动作2
...
done
示例
1, 猜商品价格, 通过变量 RANDOM 获取随机数价格, 提示用户猜测并记录次数, 猜中后退出循环
vim price.sh
#!/bin/bash
PRICE=$[ $RANDOM % 100 ]
TIMES=0
while true
do
read -p "please enter the product price [0-99] : " INT let TIMES++"
if [ $INT -eq $PRICE ]
then
echo "Good luck,you guessed it."
echo "You have guessed $TIMES times."
exit 0
elif [ $INT -gt $PRICE ]
then
echo "$INT is too high"
else
echo "$INT is too low"
fi
done
2, 在文件中记录了用户名的名称, 请根据文件记录的用户名建立用户
vim userlist
user1
user2
user3
sh demo_while.sh userlist
#!/bin/bash
[ -z "$1" ] && { exit }
exec < $1
while read USERNAME
do
useradd -r $USERNAEM && ehco $USERNAEME is created
done
3, 将之前用 for 语句创建的 test01-test30 用户删除
vim del_user.sh
#!/bin/bash
i=1
while [ $i -le 30 ]
do
if [ $i -le 9 ]
then
user=test0$i
else
user=test$i
fi
if id -u $user $>/dev/null
then
userdel -r $user
else
echo "$user is not exists..."
fi
let i++
done