试图从文本文件创建用户,但在Ubuntu中不断出现无效用户名错误



我现在正试图从一个文本文件在Ubuntu中创建用户,它看起来像这样:

student1
student2
student3
student4
student5

然而,我不断收到无效的用户名错误。例如"seradd:无效用户名"student5

这是我的密码。第一个参数是输入文件,第二个输入是输出文件。有人能帮忙吗?

#!/bin/bash
if test ${#} -lt 1 
then
echo "Please provide the input file"
exit 1
else
cat ${1} | while read user
do
randompw=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)
useradd -m -s /bin/bash ${user}
echo ${newuser}:${randompw} | chpasswd
if test $# -lt 2
then
echo ${newuser}:${randompw} >> pwlist.txt
else
echo ${newuser}:${randompw} >> ${2}
fi
if id -u ${user}
then
echo "User account ${user} created successfully"
else
echo "User account ${user} created unsuccessfully"
fi
done
fi

未定义变量newuser。我想你指的是$user

建议:

  • 将变量引用和计算用双引号括起来。我搞定了
#!/bin/bash
if test ${#} -lt 1
then
echo "Please provide the input file"
exit 1
else
cat "${1}" | while read user
do
randompw="$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)"
useradd -m -s /bin/bash "${user}"
echo "${user}:${randompw}" | chpasswd
if test $# -lt 2
then
echo "${user}:${randompw}" >> pwlist.txt
else
echo "${user}:${randompw}" >> ${2}
fi
if id -u "${user}"
then
echo "User account ${user} created successfully"
else
echo "User account ${user} created unsuccessfully"
fi
done
fi

相关内容

最新更新