Shell script loop small case 1

for

1. Create login accounts for these users and set default passwords based on the list of employees given

First, you need to have a user list file for testing, which is used to specify variables in the script.

[root@server2 ~]# vi users.txt 
aa
bb
cc
dd  //员工名单,后续可根据需要添加新的员工,再执行脚本创建用户
~  

Write a script to create users in the employee list cyclically, and set the default password 123456

[root@server2 ~]# vi useradd.sh
#!/bin/bash
ULIST=$(cat /root/users.txt)   //将员工名单赋值给变量ULIST
for UNAME in $ULIST            //将名单里的员工循环赋值给变量UNAME
do
useradd $UNAME                 //创建用户
echo "123456" | passwd --stdin $UNAME &> /dev/null //设置默认密码,执行结果不显示在执行界面
done
[root@server2 ~]# chmod +x useradd.sh   //添加执行权限
[root@server2 ~]# ./useradd.sh          //执行脚本
[root@server2 ~]# tail -10 /etc/passwd    //验证并查看创建的用户`

Check the result, the user is successfully created and you can log in to the host with the 123456 password.

Insert picture description here

2. Back up the files in the home directory, delete the account of the resigned employee and the home directory together

First, you need to have a list of resigned employees, and create a file for verification in one of the employee directories

[root@client1 ~]# vi users1.txt
aa
bb
cc
dd
[root@client1 ~]# vi uesrdel.sh     //创建删除用户脚本
#!/bin/bash
ulist=$(cat /root/users1.txt)   //获取离职员工名单
for uname in $ulist         //遍历名单中的员工  
do                      
  a=`ls -lh /home/$uname | awk '{print $2}'`    //获取员工宿主目录下的内存占用大小
  if [ "$a" != "0" ]                    //如果用量不为0,说明有文件在其中,
  then cp -r /home/$uname /userfile_backup       //备份目录下的文件
  fi
  userdel -r $uname &> /dev/null           //连带宿主目录删除用户
done
~ 
[root@client1 ~]# chmod +x uesrdel.sh    
[root@client1 ~]# ./uesrdel.sh       //执行脚本

Validation results
Insert picture description here

while

1. Add 20 users, the names are stu1, stu2...

[root@client1 ~]# vi stu.sh
#!/bin/bash
i=1
while [ $i -le 20 ]     //控制循环次数,创建的用户数    
do
  uname="stu$i"      //赋值用户名给变量
  useradd $uname     
  let i++
done
~      

Validation results
Insert picture description here

Second, guess the price of goods

[root@client1 ~]# vi pricegame.sh
#!/bin/bash
price=$(expr $RANDOM % 1000)   //利用系统的随机变量随机赋值一个价格,取余结果在0-999之间
times=0                    //统计猜测次数首先赋值为1
echo "商品的实际价格在0-999之间,猜猜是多少"
while true                //true 作为无限循环,因为不知道猜测次数
do
  read -p "请输入你猜测的价格:" INT      //提示从键盘输入价格
  let times++                         //一次价格,猜测次数加一次,times=times+1
  if [ $INT -eq $price ] ; then       //价格相等时
    echo "答对了,实际价格是$price,你总共猜测了$times次" 
    exit 0                            //猜对时用exit 0 退出循环
  elif [ $INT -gt $price ] ; then     //输入价格大于实际价格
    echo "太高了"
  else                //输入价格小于实际价格
    echo "太低了"
  fi
done
[root@client1 ~]# chmod +x pricegame.sh  //添加执行权限

Test Results
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41786285/article/details/108728005