[英]Linux Shell script to add a user with a password from a list
I'm trying to modify a script that read usernames/password from a file which is like this: 我正在尝试修改一个从文件中读取用户名/密码的脚本,如下所示:
user1 pass1
user2 pass2
user3 pass3
I can't get the script to read the space between the users and pass. 我无法获取脚本来读取用户之间的空间并通过。 What can I use to delimit this space? 我可以用什么来划定这个空间? This is my code: 这是我的代码:
for row in `cat $1`
do
if [ $(id -u) -eq 0 ]; then
username=${row%:*}
password=${row#*:}
#echo $username
#echo $password
I know I have to change the stuff in ${row%: } and ${row%: } 我知道我必须更改$ {row%: }和$ {row%: }中的内容
What do I have to put so it sees the space between user1 pass1 ? 我必须放置什么才能看到user1 pass1之间的空间?
It would be easier to split the two fields as you read each line. 阅读每一行时,将两个字段拆分会更容易。 You can do that with read
. 您可以使用read
做到这一点。 It's also better to use a while
loop here (a for loop requires to play with $IFS
and it would also load the entire file in memory): 最好while
此处使用while
循环(for循环需要使用$IFS
进行播放,并且还会将整个文件加载到内存中):
#!/bin/bash
if [ "$EUID" -ne 0 ]; then
echo >&2 "You are not root"
exit 1
fi
while read -r username password; do
# do the useradd stuff here
done < "$1"
Notice that I also changed $(id -u)
to $UID
which should be faster since it does not invoke an external program. 注意,我也将$(id -u)
更改$(id -u)
$UID
,这应该更快,因为它不会调用外部程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.