[英]Creating Users from a text file using Bash
I've been looking at some of the other answers for this question but it hasn't solved my issue. 我一直在寻找这个问题的其他答案,但它并没有解决我的问题。
Basically, I need to create a script that reads from a text file, that is given by a user input, and creates users from the contents of the file. 基本上,我需要创建一个脚本,该脚本从用户输入给出的文本文件中读取,并从文件内容创建用户。 I've managed to get it to create the first user but it doesn't seem to be creating the other users in the file. 我设法让它创建了第一个用户,但似乎并没有在文件中创建其他用户。
My text document is literally: 我的文字文件的字面意思是:
user1
user2
user3
And heres the code I have: echo -n "Enter name of text file "; read text while read USER; do USERNAME=$(cut -d$'\\n' -f $text) echo $USERNAME useradd -m "${USERNAME}" done < $text
这是我的代码: echo -n "Enter name of text file "; read text while read USER; do USERNAME=$(cut -d$'\\n' -f $text) echo $USERNAME useradd -m "${USERNAME}" done < $text
echo -n "Enter name of text file "; read text while read USER; do USERNAME=$(cut -d$'\\n' -f $text) echo $USERNAME useradd -m "${USERNAME}" done < $text
It seems to only be reading the very first entry in the text file but I thought using the \\n would mean it cut the other lines and use them next? 看来似乎只读取文本文件中的第一个条目,但是我认为使用\\ n意味着它会剪切其他行并在接下来使用它们? I tried using the 'cat' command instead but wasn't having much luck with it and this is the furthest I've managed to get but I was hoping someone would help me find where I've gone wrong. 我尝试改用'cat'命令,但运气不佳,这是我所能获得的最大成功,但我希望有人能帮助我找出问题所在。 Thanks :) 谢谢 :)
您可以使用awk
进行打印并将其通过管道传递给外壳
$ awk '{print "useradd -m "$1}' <file> | sh
First, you should start your script with 首先,您应该使用
#!/usr/bin/env bash
to ensure that it is interpreted as bash. 确保将其解释为bash。
Second, the value you need is already available in the USER
variable. 其次,所需的值已经在USER
变量中可用。 There is no need to use cut
. 无需使用cut
。
#!/usr/bin/env bash
echo -n "Enter name of text file: "; read FILENAME
while read USER; do
echo "$USER"
useradd -m "${USER}"
done < "${FILENAME}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.