Linux Shell 通过传参的方式往/etc/user.conf里添加用户

实现通过传参的方式往/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

转载于:https://blog.51cto.com/252885/2327806

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值