码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2018-12-08 23:50:14      阅读:316      评论:0      收藏:0      [点我收藏+]

标签:要求   答案   不能   lease   grep   user   用户   success   输入参数   

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

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

标签:要求   答案   不能   lease   grep   user   用户   success   输入参数   

原文地址:http://blog.51cto.com/252885/2327806

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!