1. 程式人生 > >剛開始接觸腳本,一道腳本練習

剛開始接觸腳本,一道腳本練習

腳本

題目:編寫一個腳本/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


剛開始接觸腳本,一道腳本練習