实现通过传参的方式往/etc/user.conf里添加用户,具体要求如下: 1)命令用法: USAGE: sh adduser {-add|-del|-search} username 2)传参要求: 如果参数为-add时,表示添加后面接的用户名, 如果参数为-del时,表示删除后面接的用户名, 如果参数为-search时,表示查找后面接的用户名, 3)如果有同名的用户则不能添加,没有对应用户则无需删除,查找到用户以及没有用户时给出明确提示。 4)/etc/user.conf不能被所有外部用户直接删除及修改

分析 1、判断文件是否存储,不存在先创建;判断用户执行次脚本时传参格式是否符合要求,包括:a、参数是否是2个,可以通过$#判断;b、格式是否符合要求,是否为-add username;c、执行脚本的用户是否为root 2、因为添加、删除、查询用户前要先判断用户是否存在文件中,一次有2个判断条件,不考虑用case语句,可以用if..else..,先对符合要求的进行判断,其余的做else处理

注意 判断用户是否存在文件中我使用了grep "^$2$" $file | wc -l,^$2$是为了精准匹配,避免删除用户wang,将wang1、wang2、wang3都删除;且改语句要放在对用户输入参数判断之后,确保有参数$2,否则grep会卡死。

答案: #!/bin/bash

file="/etc/user.conf" if [ ! -f $file ];then touch $file elif [ $# -ne 2 ];then echo "USAGE: sh adduser {-add|-del|-search} {username|"username"}" exit 0 elif [ ! "$UID" = 0 ];then echo "Please use the root user operation" exit 0 fi

comp=grep "^$2$" $file | wc -l

if [ $1 = "-add" -a $comp -ne 1 ];then echo $2>>$file && echo "Account $2 add successfule!!" elif [ $1 = "-add" -a $comp -eq 1 ];then echo "Account $2 exist,add fail!" elif [ $1 = "-del" -a $comp -ge 1 ];then sed -i "/^$2$/d" $file && echo "Account $2 delete successful!!!" elif [ $1 = "-del" -a $comp -lt 1 ];then echo "Account $2 dose not exist,delete fail!" elif [ $1 = "-search" -a $comp -ge 1 ];then echo "Account grep "^$2$" $file is exist" elif [ $1 = "-search" -a $comp -ne 1 ];then echo "Account $2 does not exist!" else echo "USAGE: sh adduser {-add|-del|-search} username" exit 0 fi