我需要写一个 bash 脚本
root
检查是否以用户身份运行- 询问用户名
- 检查用户是否存在
- 添加新用户和密码
- 求群名
- 检查该组是否存在
- 将用户添加到组中
我写了这样的代码
function create_user() {
if (( $EUID == 0)); then
echo "Only for root users."
exit
fi
echo "User name: "
read userschool
for x in $(awk -F":" '{ print }' /etc/passwd ); do
if [ $x == userschool ] ; then
echo "This user exists"
sleep $delay_time && exit
fi
done
sudo useradd -p $(openssl passwd -1 $PASS) $userschool
echo "User has been added"
sleep $delay_time
echo "Name of group"
read school
for x in $(awk -F":" '{ print }' /etc/group ); do
if [ $x == school ] ; then
echo "Group doesn't exists"
else
echo "$userschool has been added to group $school"
sleep $delay_time
break 2
fi
done
}
它几乎可以工作,但如果用户存在,脚本还会再次添加他,我不知道为什么。我想传达用户存在并停止的信息。
答案1
您正在$x
与文字userschool
而不是变量进行比较。你应该双引号你的变量调用防止通配和分词。它应该是 :
if [ "$x" == "$userschool" ]; then
...
fi
if [ "$x" == "$school" ]; then
...
fi
而且您不必迭代整个 /etc/passwd 并逐行进行比较。相反,只需执行以下操作:
awk -F: -v user=$userschool '$1 == user {print $1}' /etc/passwd
-v
awk 中的变量赋值在哪里。
如果它已经存在,那么它将输出给定的用户名
# Since it's bash, you can do this instead
read -p "Username: " userschool
exists=$(awk -F: -v user=$userschool '$1 == user {print $1}' /etc/passwd)
if [[ "$exists" ]]; then
echo "User exists."
sleep $delay_time
exit 1
fi
# create user
...
答案2
主要问题是
awk -F":" '{ print }' /etc/passwd
打印整行。一定是
awk -F":" '{ print $1; }' /etc/passwd
并且你忘记了$
in $x == userschool
。"$x" = "$userschool"
当然,一定是这样。
exit
此外,调用没有意义
sleep $delay_time && exit
因为你希望exit
在任何情况下都被执行。但如果有问题sleep
(例如,如果您忘记设置delay_time
或给它一个非法值),则不是。所以应该是
E_USER_EXISTS=3
if [ "$x" = "$userschool" ] ; then
echo "This user exists"
sleep "$delay_time"
exit "$E_USER_EXISTS"
fi
尽管如此,这是一个糟糕的方法。稍后我会推荐一个更好的。
答案3
默认情况下,如果用户已经存在,useradd 命令会抛出错误...您不必重新检查它...
function create_user() {
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
echo -n "User name: "
read userschool
sudo useradd -p $(openssl passwd -1 $PASS) $userschool && echo "User has been added"
sleep $delay_time
echo "Name of group"
read school
sudo groupadd $school &>>/dev/null && echo "Group created $school"
sudo usermod -aG $school $userschool
}