概述
shell是一个命令解释器,是一个程序/bin/bash,解释linux的命令,而shell脚本是一系列的命令组成的文件,想要熟练掌握shell脚本,唯有不断练习,接触各种各样的需求并用shell来实现才可以。
需求
利用case语句编写脚本,满足下列要求
1.执行create时根据userfile和passfile建立用户
2.执行delete时根据userfile删除用户
1、脚本内容:
# vim user_ctrl.sh#!/bin/bashread -p "Please input the operation (create or delete ): " OPERATION //输入你要执行的动作case $OPERATION in create) //第一种情况:create read -p "Please input the userfile : " USERFILE //提示输入文件 [ -e $USERFILE ] || { //判断是否存在 echo "$USERFILE is not exist " exit 1 } read -p "Please input the passwdfile : " PASSFILE [ -e $PASSFILE ] || { echo "$PASSFILE is not exist " exit 1 } USERLINE=`awk 'BEGIN{N=0}{N++}END{print N}' $USERFILE` //计算userfile文件行数 for LINE_NUM in `seq 1 $USERLINE` //利用循环建立 do USERNAME=`sed -n "${LINE_NUM}p" $USERFILE` //截取userfile文件第一行内容 PASSWORD=`sed -n "${LINE_NUM}p" $PASSFILE` //截取passfile文件第一行内容 useradd $USERNAME //建立用户 echo $PASSWORD | passwd --stdin $USERNAME done ;; delete) //第二种情况:delete read -p "Please input the userfile : " USERFILE [ -e $USERFILE ] || { echo "$USERFILE is not exist " exit 1 } USERLINE=`awk 'BEGIN{N=0}{N++}END{print N}' $USERFILE` for LINE_NUM in `seq 1 $USERLINE` do USERNAME=`sed -n "${LINE_NUM}p" $USERFILE` userdel -r $USERNAME done ;; *) //第三种情况:其余各种情况 echo Error! ;;esac
![df219b2a1e47e4305c08846821df4742.png](https://i-blog.csdnimg.cn/blog_migrate/6df604129fca97b999a2fec8379adf14.jpeg)
2、执行:
[root@localhost mnt]# cat userfile user1user2user3[root@localhost mnt]# cat passfile 123456789[root@localhost mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): hello //输入错误动作Eorror![root@localhost mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): createPlease input the userfile : user //输入错误文件user is not exist [root@localhost mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): createPlease input the userfile : userfilePlease input the passwdfile : passfile //建立用户Changing password for user user1.passwd: all authentication tokens updated successfully.Changing password for user user2.passwd: all authentication tokens updated successfully.Changing password for user user3.passwd: all authentication tokens updated successfully.[root@localhost mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): delete //删除用户Please input the userfile : userfile[root@localhost mnt]# id user1id: user1: no such user
![551e376c122c4ac0c114f2cd3e0bb693.png](https://i-blog.csdnimg.cn/blog_migrate/ec713c65d99a1da4d274d25ade558442.jpeg)
![a9676ed9f627e5c19e58eac18cfa0318.png](https://i-blog.csdnimg.cn/blog_migrate/bc26bdf477401f7d7eb9221879a9c85e.jpeg)
关于shell脚本就介绍到这了,大家在看需求的时候建议自己先写一下,然后再对着改进,效果会好一点。后面小编会分享更多linux方面内容,感兴趣的朋友走一波关注哩~
![6bdbe914f206356020abf19856350d85.gif](https://i-blog.csdnimg.cn/blog_migrate/9fe2fc9a4a65d9e7e9d12264954adfe0.gif)