Linux Shell 用于从列表中添加具有密码的用户的脚本
Linux Shell script to add a user with a password from a list
我正在尝试修改从文件中读取 usernames/password 的脚本,如下所示:
user1 pass1
user2 pass2
user3 pass3
我无法让脚本读取用户之间的 space 并通过。
我可以用什么来分隔这个space?
这是我的代码:
for row in `cat `
do
if [ $(id -u) -eq 0 ]; then
username=${row%:*}
password=${row#*:}
#echo $username
#echo $password
我知道我必须更改 ${row%:} 和 ${row%:}
中的内容
我必须输入什么才能看到 user1 pass1 之间的 space?
当您阅读每一行时,拆分两个字段会更容易。您可以使用 read
来做到这一点。最好在这里使用 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 < ""
请注意,我还将 $(id -u)
更改为 $UID
,这应该更快,因为它不调用外部程序。
我正在尝试修改从文件中读取 usernames/password 的脚本,如下所示:
user1 pass1
user2 pass2
user3 pass3
我无法让脚本读取用户之间的 space 并通过。 我可以用什么来分隔这个space? 这是我的代码:
for row in `cat `
do
if [ $(id -u) -eq 0 ]; then
username=${row%:*}
password=${row#*:}
#echo $username
#echo $password
我知道我必须更改 ${row%:} 和 ${row%:}
中的内容我必须输入什么才能看到 user1 pass1 之间的 space?
当您阅读每一行时,拆分两个字段会更容易。您可以使用 read
来做到这一点。最好在这里使用 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 < ""
请注意,我还将 $(id -u)
更改为 $UID
,这应该更快,因为它不调用外部程序。