概述

shell是一个命令解释器,是一个程序/bin/bash,解释linux的命令,而shell脚本是一系列的命令组成的文件,想要熟练掌握shell脚本,唯有不断练习,接触各种各样的需求并用shell来实现才可以。


需求

利用case语句编写脚本,满足下列要求

1.执行create时根据userfile和passfile建立用户

2.执行delete时根据userfile删除用户


1、脚本内容:

# vim user_ctrl.sh #!/bin/bash read -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

shell脚本语句怎么写(如何利用case语句编写shell脚本)(1)


2、执行:

[root@localhost mnt]# cat userfile user1 user2 user3 [root@localhost mnt]# cat passfile 123 456 789 [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 ): create Please input the userfile : user //输入错误文件 user is not exist [root@localhost mnt]# sh user_ctrl.sh user Please input the operation (create or delete ): create Please input the userfile : userfile Please 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 user1 id: user1: no such user

shell脚本语句怎么写(如何利用case语句编写shell脚本)(2)

shell脚本语句怎么写(如何利用case语句编写shell脚本)(3)


关于shell脚本就介绍到这了,大家在看需求的时候建议自己先写一下,然后再对着改进,效果会好一点。后面小编会分享更多linux方面内容,感兴趣的朋友走一波关注哩~

shell脚本语句怎么写(如何利用case语句编写shell脚本)(4)

,