shell脚本在Linux中添加用户

时间:2020-03-05 15:31:48  来源:igfitidea点击:

在本教程中,我们将展示如何编写shell脚本以在Linux中添加用户。
在脚本中,我们将使用UserAdd命令添加user和groupadd命令以将用户添加到组。

使用shell脚本添加新用户

以下shell脚本添加一个新用户,可以创建用户名,主组,主目录和shell。
我们正在使用useradd命令来创建用户。

#!/bin/bash
while [ x$username = "x" ]; do
read -p "Please enter the username you wish to create : " username
if id -u $username >/dev/null 2>&1; then
echo "User already exists"
username=""
fi
done
while [ x$group = "x" ]; do
read -p "Please enter the primary group. If group not exist, it will be created : " group
if id -g $group >/dev/null 2>&1; then
echo "Group exist"
else
groupadd $group
fi
done
read -p "Please enter bash [/bin/bash] : " bash
if [ x"$bash" = "x" ]; then
bash="/bin/bash"
fi
read -p "Please enter homedir [/home/$username] : " homedir
if [ x"$homedir" = "x" ]; then
homedir="/home/$username"
fi
read -p "Please confirm [y/n]" confirm
if [ "$confirm" = "y" ]; then
useradd -g $group -s $bash -d $homedir -m $username
fi

示例结果

sudo ./linux_user.sh
Please enter the username you wish to create : test
Please enter the primary group. If group not exist, it will be created : test
Please enter bash [/bin/bash] :
Please enter homedir [/home/test] :
Please confirm [y/n]y
22:12:58 [test@Desktop] :~ id test
uid=1003(test) gid=1003(test) groups=1003(test)