zoukankan      html  css  js  c++  java
  • while

    while基础

    for循环可以指定次数,而while通常是无限的,只要条件为真就会一直向下执行。

    i=0
    while [ $i -lt 10 ]
    do
            echo 123
            let i++
    done
    
    
    执行效果
    [root@test2 tmp]# /bin/bash 1.sh
    123
    123
    123
    123
    123
    123
    123
    123
    123
    123
    
    i=0
    while [ $i -le 5 ]
    do
    	echo $i
    	let i++
    done
    [root@test2 tmp]# /bin/bash 2.sh
    0
    1
    2
    3
    4
    5
    
    i=5
    while [ $i -ge 1 ]
    do
    	echo $i
    	let i--
    done
    [root@test2 tmp]# /bin/bash 2.sh
    5
    4
    3
    2
    1
    
    a=1
    b=10
    while [ $a -le 10 ]
    do
    	echo $a $b
    	let a++
    	let b--
    done
    [root@test2 tmp]# /bin/bash 2.sh
    1 10
    2 9
    3 8
    4 7
    5 6
    6 5
    7 4
    8 3
    9 2
    10 1
    
    a=1
    b=10
    while [ $a -le 10 ]
    do
    	sum=$(($a+$b))
    	echo $a+$b=$sum
    	let a++
    	let b--
    done
    [root@test2 tmp]# /bin/bash 2.sh
    1+10=11
    2+9=11
    3+8=11
    4+7=11
    5+6=11
    6+5=11
    7+4=11
    8+3=11
    9+2=11
    10+1=11
    
    a=1
    b=10
    while [ $a -le 10 ]
    do
    	sum=$(( $a-$b ))
    	echo $a-$b=$sum
    	let a++
    	let b--
    done
    [root@test2 tmp]# /bin/bash 2.sh
    1-10=-9
    2-9=-7
    3-8=-5
    4-7=-3
    5-6=-1
    6-5=1
    7-4=3
    8-3=5
    9-2=7
    10-1=9
    

    取行-批量添加用户

    for是按照空格取值,而while是按行取值

    示例1:用while循环批量创建用户

    [root@test2 tmp]# cat user.txt 
    user1
    user2
    user3
    [root@test2 tmp]# cat 3.sh  
    while read line     #read是命令,line是变量,一行就是一个变量
    do
    	id $line &> /dev/null
    	if [ $? -eq 0 ];then
    		echo "用户已经存在!"
    	else
    		useradd $line &> /dev/null && echo "用户增加成功"
    	fi
    done < /tmp/user.txt
    [root@test2 tmp]# /bin/bash 3.sh
    用户已经存在!
    用户已经存在!
    用户已经存在!
    

    示例2:批量添加用户并指定密码

    [root@test2 tmp]# cat user.txt 
    user1 123
    user2 121
    user3 321
    root@test2 tmp]# cat 3.sh 
    while read line
    do
    	user=$(echo $line|awk '{print $1}')
    	pass=$(echo $line|awk '{print $2}')
    	id $user &> /dev/null
    	if [ $? -eq 0 ];then
    		echo "$user用户已经存在!"
    	else
    		useradd $user &> /dev/null && echo "$user用户增加成功"
    		echo $pass | passwd --stdin $user &>/dev/null
    	fi
    done < /tmp/user.txt
    [root@test2 tmp]# /bin/bash 3.sh
    user4用户已经存在!
    user5用户已经存在!
    user6用户已经存在!
    

    示例3:批量添加用户,用随机密码

  • 相关阅读:
    题解 nflsoj204 排列
    题解 CF1328 D,E,F Carousel, Tree Queries, Make k Equal
    题解 LOJ3277 「JOISC 2020 Day3」星座 3
    题解 nflsoj464 CF1267K 正睿1225:一个简单的计数技巧
    题解 CF1326F2 Wise Men (Hard Version)
    题解 CF1326E Bombs
    题解 CF1316E and UOJ495:一类结合贪心的背包问题
    仓鼠的DP课 学习笔记
    题解 CF1314B Double Elimination
    固件
  • 原文地址:https://www.cnblogs.com/yizhangheka/p/12562189.html
Copyright © 2011-2022 走看看