第七章实验(三):while+case

一.while循环:

重复测试摸个条件,只要条件成立反复执行。

条件可以是:测试表达式,也可以是布尔值true(条件永远为真)和false(条件永远为假)

[[email protected] bin]# cat useradd_while.sh ##将下面脚本改写为新建用户的脚本

#!/bin/bash

PRE=stu

i=0

while [ $i -le 10 ];do

#useradd $PRE$i

#echo 123123 |passwd --stdin $PRE$i

userdel -r $PRE$i

#i=$(expr $i + 1)

let i++

done

刘启成_第七章实验(三):while

刘启成_第七章实验(三):while

1.函数RANDOM、let、exit:

RANDOM是生成随机数的一个函数。

[[email protected] bin]# echo $RANDOM ##生成随机数

刘启成_第七章实验(三):while

[[email protected] bin]# expr $RANDOM % 100 ##获取100内的随机数

27

刘启成_第七章实验(三):while

[[email protected] bin]# expr $RANDOM % 1000 ##获取1000内的随机数

336

let命令的作用是对变量进行自加减操作:

[[email protected] bin]# i=1

[[email protected] bin]# let i++

[[email protected] bin]# echo $i

2

[[email protected] bin]# let ++i

[[email protected] bin]# echo $i

3

[[email protected] bin]# let i--

[[email protected] bin]# echo $i

2

刘启成_第七章实验(三):while

[[email protected] bin]# expr $i + 1

刘启成_第七章实验(三):while

综合应用:

[[email protected] bin]# cat price_guess.sh

#!/bin/bash

PRICE=$(expr $RANDOM % 1000)

TMS=0

echo "please insert a number like this(1-999)"

while true;do

read -p "please give number:" INT

let TMS++

if [ $INT -eq $PRICE ];then

echo "your luckly. right! "

echo "Your guess $TMS"

exit 0

elif [ $INT -gt $PRICE ];then

echo "Too High,try a again. "

else

echo "Too low,try a again."

fi

done

刘启成_第七章实验(三):while

刘启成_第七章实验(三):while

2.区分exit,break

exit退出程序(脚本),break只是退出循环体。

[[email protected] bin]# cat die_while.sh

#!/bin/bash

i=0

j=$(expr $RANDOM % 10)

while true;do

echo $i

let i++

sleep 1 ##休眠1秒避免死循环产生

if [ $i -eq $j ];then

echo "ok,$j random"

break ##将break替换为exit执行后查看效果

fi

done

df -hT

[[email protected] bin]#

刘启成_第七章实验(三):while

刘启成_第七章实验(三):while

刘启成_第七章实验(三):while

刘启成_第七章实验(三):while

转载于:https://blog.51cto.com/liuqicheng/1874373

相关文章:

  • 2021-06-28
  • 2021-07-22
  • 2021-07-04
  • 2021-08-17
  • 2021-04-09
  • 2022-02-02
  • 2021-05-28
  • 2021-07-29
猜你喜欢
  • 2021-04-14
  • 2021-11-27
  • 2021-04-24
  • 2022-12-23
  • 2021-12-06
  • 2021-05-27
  • 2021-12-27
相关资源
相似解决方案