首页 > 代码库 > 刚开始接触脚本,一道脚本练习
刚开始接触脚本,一道脚本练习
题目:编写一个脚本/root/bin/createuser.sh,脚本的执行语法必须是:createuser.sh -u username -m password,选项与参数间可支持多空格,但不能顺序颠倒。 当未指定正确的选项或参数时,以错误输出方式提示“createuser.sh -u username -m password ”后退出脚本。用户名必须以字母开头,可包括数字和_,否则不合法,以错误输出提示用户"用户名仅包含字母数据和下划线"。当用户名检测合法后,判断用户名是否已存在,若存在,再判断用户是否已设置过密码,若设置过密码,直接退出,未设置,则将密码设置为所指定的密码后以正确输出方式显示“username 密码已更新后退出”。当用户名不存在,则创建用户,并为该用户设置所指定的密码后以正确输出方式显示“用户username已创建并更新密码”,要求脚本执行过程中不能有非要求的其他输出结果出现。脚本在非正确方式退出时应反回给?参数非0值。
自己的尝试:
#/bin/bash
#------------------------------
#Filename:createuser.sh
#Revision:1.0
#Data:2017-08-05
#Author:Jun
#Description:create user and set passworld
#------------------------------
#confirm the parameters
if [ "$1" == "-u" -a "$3" == "-m" ]; then
echo "true" > /dev/null
else
echo "createuser -u username -m passed"
exit 1
fi
if [ -n "$5" ]; then
echo "createuser -u username -m passed"
exit 1
fi
#judge username
first=`echo $2| grep -o ^.`
if [[ "$2" =~ "[^[:alpha:]_0-9]" ]]; then
echo "please use A-Z, a-z, _, or 0-9 for username"
exit 1
elif [[ "$first" =~ "[^[:alpha:]]" ]]; then
echo "please use an English letter as the begining for username"
exit 1
fi
#judge whether exist
username=`cat /etc/passwd| grep -o "^$2\>"`
#user exist
if [ "$username" == "$2" ]; then
passwd=`cat /etc/shadow| grep "^$2\>"| cut -d ":" -f 2`
#passworld is empty
if [ "!!" == "$passwd" ]; then
echo $4| passwd --stdin $username > /dev/null
echo "$username‘s passworld updated"
#passworld already existed
else
echo "can‘t set passworld for $username because of passworld existence"
fi
#user not exist
else
useradd $2
echo $4| passwd --stdin $2 > /dev/null
echo "created user $2 successfully and updated the passworld"
fi
unset username passwd
exit 0
刚开始接触脚本,一道脚本练习