1.while介绍
while循环是先执行一次即do一次,出循环体时候判断while条件是否为真真,跳到do继续循环;假,退出循环,执行下一行代码
while是计算机的一种基本循环模式。当满足条件时进入循环,进入循环后,当条件不满足时,跳出循环。while语句的一般表达式为:while(表达式){循环体}
2.while循环详解
在Shell脚本中,while循环是一种用于重复执行一段代码块的控制结构。while循环会在指定的条件为真时重复执行代码块,直到条件为假为止。
while循环的基本语法如下:
在这个语法中,condition是一个用于判断循环是否继续执行的表达式。只要condition的值为真(非零),循环就会继续执行代码块。一旦condition的值为假(0),循环就会终止。
下面是一个使用while循环的示例:
在这个示例中,while循环会在counter小于等于5时持续执行。在每次循环中,会输出当前的计数器值,并将计数器增加1。当计数器达到5时,循环会终止。
需要注意的是,在while循环中,如果条件永远为真,循环将会无限循环下去,直到手动终止脚本的执行或达到系统资源限制。因此,确保在循环中更新条件,以避免无限循环的发生。
3.案例
true命令
[root@shell /server/scripts]$ cat while1.sh
#!/bin/bash
while true
do
echo “This will run indefinitely until manually stopped.”
sleep 1
done
true是一个Unix/Linux系统中的一个命令,用于始终返回成功(退出状态码为0)。在Shell脚本中,true命令通常用于创建一个永远为真的条件,常用于while循环中。
在这个示例中,while true创建了一个永远为真的条件,因此循环会无限循环下去,直到手动终止脚本的执行。在每次循环中,会输出一条消息并休眠1秒。这种用法可以用来实现一些需要持续运行的任务,比如监控系统状态或实时处理数据等。
需要注意的是,使用true命令创建无限循环时,要确保有合适的终止条件或手动停止脚本的执行,以避免资源浪费或系统负载过高。
从1加到100
[root@shell /server/scripts]$ cat whileshu.sh
#!/bin/sh
i=1
while [ 100 -ge $i ]
do
count=$[count+i]
let i++
done
echo $count
[root@shell /server/scripts]$ sh whileshu.sh
5050
创建用户
[root@shell /server/scripts]$ cat user.txt
tiedan 123
heidan 456
goudan 789
gousheng 987
gangzi 654
#!/bin/sh
while read line
do
user=`echo $line|awk ‘{print $1}’`
pass=`echo $line|awk ‘{print $2}’`
useradd $user
if [ $? -eq 0 ];then
echo “$user创建成功”
echo $pass|passwd –stdin $user &>/dev/null
[ $? -eq 0 ] && echo “密码创建成功”
echo -e “$user\t$pass” >> passwd.txt
else
echo “用户已存在”
fi
done[root@shell /server/scripts]$ sh whileuser.sh
tiedan创建成功
密码创建成功
heidan创建成功
密码创建成功
goudan创建成功
密码创建成功
gousheng创建成功
密码创建成功
gangzi创建成功
密码创建成功
[root@shell /server/scripts]$ cat passwd.txt
tiedan 123
heidan 456
goudan 789
gousheng 987
gangzi 654
[root@shell ~]$ su – gousheng
[gousheng@shell ~]$ su – tiedan
Password:
Last failed login: Fri May 10 00:06:43 CST 2024 on pts/1
There was 1 failed login attempt since the last successful login.
[root@shell /server/scripts]$ tail -5 /etc/passwd
tiedan:x:1001:1001::/home/tiedan:/bin/bash
heidan:x:1002:1002::/home/heidan:/bin/bash
goudan:x:1003:1003::/home/goudan:/bin/bash
gousheng:x:1004:1004::/home/gousheng:/bin/bash
gangzi:x:1005:1005::/home/gangzi:/bin/bash