您的位置:首页 > 运维架构 > Shell

shell脚本练习之while

2020-07-29 20:22 615 查看

刚开始学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的两种用法,代码仅供参考>

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: