我现在尝试从文本文件在 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
您能找到解决方案吗?
抱歉,我想不出其他方法来问你..