Linux使用bash(shell)脚本添加用户

it2026-01-19  7

通过bash脚本添加用户

脚本接受两个参数:username、[password]

username必填,password选填写,未填写password时,用户名和密码都是username

创建脚本

创建文件

vi adduser.sh

添加内容:

#! /bin/bash # example ./adduser.sh username [password] [ $# -eq 0 ] && echo "At least one paramter is required!" && exit 1 id $1 >& /dev/null && echo "user '$1' already exists!" && exit 2 useradd $1 && if test $# -eq 1; then echo $1; else echo $2; fi | passwd --stdin $1 &> /dev/null && echo "add user $1 success" && exit 0 echo "something above goes wrong" && exit 3

添加执行权限

chmod +x adduser.sh

执行脚本

#./adduser.sh username [password] ./adduser.sh djzhao passw0rd!! ./adduser.sh djzhao2

脚本说明

[ $# -eq 0 ] && echo "At least one paramter is required!" && exit 1

使用[ arg... ]条件表达式判断是否传参,$#表示参数数量,如果参数数量等于0(-eq),则终止脚本,返回错误码1


id $1 >& /dev/null && echo "user '$1' already exists!" && exit 2

使用id指令查询需要创建的用户是否存在,如果用户存在,表达式id $1的返回值($?)为0,则终止脚本,返回错误码2

其中表达式>& /dev/null可以隐藏表达式id $1的输出信息(重定向到空设备)


useradd $1 && if test $# -eq 1; then echo $1; else echo $2; fi | passwd --stdin $1 &> /dev/null && echo "add user $1 success" && exit 0

执行用户添加和设置密码,使用表达式if test $# -eq 1; then echo $1; else echo $2; fi判断用户是否设置了第二个参数,如果没有参数二,使用用户名作为密码,最终终止脚本,返回成功代码0


echo "something above goes wrong" && exit 3

能够执行到最后一行表示在useradd 或者 passwd时出现了异常,很有可能是权限不足所导致!

最新回复(0)