shell脚本练习之while

刚开始学shell?
那就肯定要学习while循环,
把下面几个练习做出来,你就学会while循环了!

  • 使用while循环,添加user1-user10,分别设置密码为pass1-pass10,不添加user5
#!/bin/bash
i=0
while [ $i -le 10 ];
do
        let i++
        if [ $i -eq 5 ];then
                continue
        fi
        useradd user${i} 1> /dev/null
        echo pass${i}|passwd --stdin user${i} > /dev/null
done
  • 使用while循环,将上题中的9个用户删除,删除成功给出如下提示“user xxx delete successfully.”
#!/bin/bash
i=1
while [ $i -le 10 ];
do
        if [ $i -eq 5 ];then
                let i++
                continue
        fi
        userdel -r  user${i} 1> /dev/null
        echo "user${i}  delete successfully."
        let i++
done
  • 使用while循环计算1+2+3+…+100
#!/bin/bash
i=1
sum=0
while [ $i -le 100 ];
do
        let sum+=i
        let i++
done
echo $sum
  • 使用while循环打印出所有用户信息,格式如下:用户名:XXX,UID:XXX,GID:XXX
while read line
do
    username=`echo ${line} | awk -F: '{print $1}'`
    userID=`echo ${line} | awk -F: '{print $3}'`    
    userGID=`echo ${line} | awk -F: '{print $4}'`    
    echo "Username: $username    UserID: $userID    UserGID: $userGID"
done < /etc/passwd
  • 使用while循环,打印出passwd文件所有的奇数行行号及内容。
#!/bin/bash
i=1
while read odd_line
do
        [ $(( ${i}%2 )) != 0 ] && echo "${i} ${odd_line}"
        let i++
done < /etc/passwd

<以上就是while的两种用法,代码仅供参考>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值