#!/bin/sh #add or del or search user #by zkg 2019-08-12 #通过传参的方式向/etc/user.conf文件里添加用户,要求如下: #(1) 命令用法如下: #USAGE:sh adduser {-add|-del|-search} username #(2) 传参要求: #如果参数为-add 则添加后面接的用户 #如果参数为-del 则删除后面接的用户 #如果参数为-search 则搜索后面接的用户 #(3) 如果有同名的用户则不能添加,没有对应用户则无需删除,查找到用户以及没有用户时给以明确提示 #(4) /etc/user.conf不能被所有外部用户删除或修改

#定义变量 USER_FILE=/etc/user.conf FIRST=$1 SECORD_USER=$2 COUNT=echo $#

#判断文件是否存在 if [ ! -f $USER_FILE ];then echo "$USER_FILE is not exist,please create file" touch $USER_FILE fi chmod 644 $USER_FILE

#判断参数个数 if [ $COUNT -ne 2 ];then echo "USAGE:sh adduser {-add|-del|-search} username" exit 1 fi #判断用户名格式

if [ "echo "$SECORD_USER"|sed -r 's/[^a-zA-Z0-9]//g'" = "$SECORD_USER" ];then echo "the $SECORD_USER format is error,can not special characters" exit 2 fi

#search funcation funCheckUser(){ CHKCOUNT=grep -w "$SECORD_USER" $USER_FILE|wc -l if [ $CHKCOUNT -eq 0 ];then return 0 else return 1 fi }

#功能模块 #添加用户 #判断用户是否存在 funAddUser(){ funCheckUser if [ $? -eq 0 ];then echo "$SECORD_USER" >> $USER_FILE else echo "the $SECORD_USER is exist..." exit 3 } #删除用户 #判断用户是否存在 funDelUser(){ funCheckUser if [ $? -eq 0 ];then echo "there is no user" else sed -ri 's/^$SECORD_USER$//d' $USER_FILE exit 4 } #搜索用户 #判断用户是否存在 funSearchUser(){ funCheckUser if [ $? -eq 0 ];then echo "no user is match" else echo "$SECORD_USER is exist..." fi } case $FIRST in -add) funAddUser;; -del) funDelUser;; -search) funSearchUser;; *) echo "USAGE:sh adduser {-add|-del|-search} username" exit esac