[英]bash script to add and remove users
我是 bash 腳本的初學者,我創建了一個 bash 腳本來在 Linux 上添加用戶和刪除用戶。 但是由於我面臨的腳本問題並不是真正的主要問題,但是如果有人能指出我如何改進腳本和最壞的做法,我正在編寫腳本會有所幫助
但是我注意到的問題是腳本需要 -a 添加用戶 -d 刪除用戶和 -h 獲取幫助 -a 標志作為 2 個可選參數 -p 用於密碼和 -s 用於 shell 所以命令將是
./useradd.sh -a user -p password -s shell
這按預期工作,用戶已添加到系統中,但我面臨的問題是,如果我不輸入 -a 標志並指定 -s 和 -p 標志,腳本剛剛退出,我想向您展示一個清晰的想法用戶為什么退出,我假設有很多這樣的錯誤,但我還沒有測試過這么多,任何幫助都將不勝感激,所以這是我的腳本
#!/bin/bash
## checking if the user is privileged or not
if [[ $EUID != 0 ]]
then
echo "Script has to be ran as root or sudo"
echo "Aborting"
exit 101
fi
## creating help functions
function usage() {
echo "usage: ${0} -a <user> -p <password> -s <shell> | ${0} -d <user> | ${0} -h"
}
function help() {
echo "$0 - Script to add of remove users"
echo "-a - Add a new user"
echo " -p - Set password while creating user if not mentioned will not set any password by default"
echo " -s - Set a shell for the user default is /bin/bash if none specified"
echo "-a - Remove a user"
echo "-h - Print this help text"
}
if [[ "$#" -lt "1" ]]; then
echo "Argument has to be provided see $0 -h"
fi
shell=/bin/bash
password=$(openssl rand -base64 32)
while getopts :a:d:h opt; do
case $opt in
a) user=$OPTARG
while getopts :p:s: test
do
case $test in
p) password=$OPTARG;;
s) shell=$OPTARG;;
/?) echo "The provided flag is not identified see $0 -h"
exit;;
:) echo "$OPTARG requires arguments see $0 -h"
exit;;
esac
done
if [[ "$1" != "-a" ]]
then
echo "You have to specify username using -a flag see $0 -h"
fi
useradd -m $user -s $shell
echo "$user":"$password" | chpasswd
echo "The password for the $user is $password";;
d) userdel -f $OPTARG
if [[ $? == 0 ]]
then
echo "user has been removed"
else
echo "There was some error removing the user"
fi;;
h) help
exit;;
/?) echo "$OPTARG option not valid";;
:) echo "$OPTARG requires argument";;
esac
done
請出示您的代碼! 我通常用 case ... in likes 處理 args :
#!/bin/bash
while [[ $# -gt 0 ]]; do
case $1 in
"-a")
echo "-a is $2"
shift 2;;
"-d")
echo "-d is $2"
shift 2;;
esac
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.