[英]how to add multiple users and afterwards add them to groups in linux using bash script
I have a txt file called Usernames.txt with such information (name followed by group type).我有一个名为 Usernames.txt 的 txt 文件,其中包含此类信息(名称后跟组类型)。 Eg (These are the few instances as there are way more inputs.)
例如(这些是少数实例,因为有更多的输入。)
Usernames.txt:用户名.txt:
ellipsiscoterie,visitor
magnetcommonest,visitor
belateddefensive,staff
wizardmeans,visitor
bobstercaramelize,staff
In the script show below, I attempted to add each line's name as a user and allocate each new user to its respective groups.在下面显示的脚本中,我尝试将每一行的名称添加为用户并将每个新用户分配到其各自的组。 However I have encountered this error.
但是我遇到了这个错误。 And the output is not what I had in mind.
输出不是我所想的。 I hope someone can help me out, thanks.
希望有人能帮帮我,谢谢。
Basically this is what I want to do but for every single lines in the txt file.基本上这就是我想要做的,但对于 txt 文件中的每一行。 Eg
sudo useradd bobstercaramelize
(which is the name of user) and sudo usermod -a -G staff bobstercaremelize
.例如
sudo useradd bobstercaramelize
(这是用户的名称)和sudo usermod -a -G staff bobstercaremelize
。
Error:错误:
createUsers.sh: line 4: $'[visitor\r': command not found
Code:代码:
#!/bin/bash
while read line; do
arrIN=(${line//,/ })
if [${arrIN[1]} = "visitor" ]; then
sudo useradd ${arrIN[0]}
sudo usermod -a -G visitors ${arrIN[0]}
else
sudo useradd ${arrIN[0]}
sudo usermod -a -G staff ${arrIN[0]}
fi
done < Usernames.txt
First, the error seems to stem from a missing space: [${arrIN[1]} = "visitor" ]
needs to be [ ${arrIN[1]} = "visitor" ]
.首先,错误似乎源于缺少空格:
[${arrIN[1]} = "visitor" ]
需要为[ ${arrIN[1]} = "visitor" ]
。 Note the space between [
and ${arrIN[1]}
.注意
[
和${arrIN[1]}
之间的空格。
Second, the \\r
in the error message indicates that there might be an issue with the line endings of your Usernames.txt
file.其次,错误消息中的
\\r
表示Usernames.txt
文件的行尾可能存在问题。 Try to save it with Unix/Linux line endings (ie each line should be terminated by \\n
only).尝试使用 Unix/Linux 行结尾保存它(即每行应仅以
\\n
结尾)。
Third, you might want to consider parsing the file's contents differently:第三,您可能需要考虑以不同方式解析文件的内容:
while IFS=, read user group; do
if [ "${group}" = "visitor" ]; then
sudo useradd "${user}"
sudo usermod -a -G visitors "${user}"
else
sudo useradd "${user}"
sudo usermod -a -G staff "${user}"
fi
done < Usernames.txt
This way, read
does the splitting for you, making things easier, more precise and more readable.这样,
read
为您进行拆分,使事情变得更容易、更精确和更具可读性。 I also added double quotes where advisable.我还在适当的地方添加了双引号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.