bash脚本来添加和删除用户

时间:2020-11-09 11:41:21

标签: linux bash shell server sh

我是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

1 个答案:

答案 0 :(得分:0)

请显示您的代码!我通常用case处理args ...:p

#!/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