【问题标题】:bash script to add and remove users用于添加和删除用户的 bash 脚本
【发布时间】:2021-02-21 07:59:56
【问题描述】:

我是 bash 脚本的初学者,我创建了一个 bash 脚本来在 Linux 上添加和删除用户。但是,由于我在脚本方面遇到了一些问题,但并不是真正的重大问题,但如果有人能指出我如何改进脚本以及我正在编写脚本的最坏做法会很有帮助

但是我注意到的问题是脚本需要 -a 来添加用户 -d 来删除用户和 -h 来获得帮助 -a 标志作为 2 个可选参数 -p 用于密码,-s 用于外壳所以命令将是

./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

【问题讨论】:

标签: linux bash shell server sh


【解决方案1】:

请出示您的代码!我通常用 case ... 处理 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 2020-03-05
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多