gpt4 book ai didi

linux - bash shell 自动创建用户 - adduser

转载 作者:太空宇宙 更新时间:2023-11-04 04:39:51 27 4
gpt4 key购买 nike

我需要通过读取包含用户名、主目录和全名的文件行来自动创建用户。

我是 bash shell 脚本新手,这让我很困惑。

我的 adduser 命令有问题。它给出错误 - adduser: 只允许一个或两个名称。

以下是完整的脚本 -

while read line;
do
fieldnumbers=$(echo $line | grep - o " " | wc - l)
username=$(echo $line | cut -d' ' -f 1)
home=$(echo $line | cut -d' ' -f 2)
firstname=$(echo $line | cut -d' ' -f 3)

if [[ "$fieldnumbers" -eq b4 ]]
then
middlename=""
else
middlename=$(echo $line | rev | cut -d' ' -f 2)

lastname=$(echo $line | rev | cut -d' ' -f 1)
password=$(echo pwgen 7 1) #create random password
fullname="$firstname $middlename $lastname"

echo "username is : $username"
sudo adduser --gecos $fullname --disabled-password --home $home $username

echo 'username:$password' | chpasswd
echo "Password is for $username is: $password"
done < users.txt

我确信这个脚本充满了语法错误。请帮忙。我的脑子都炸了。

最佳答案

始终引用变量,除非您故意要将值拆分为单独的单词。

sudo adduser --gecos "$fullname" --disabled-password --home "$home" "$username"

此外,如果您希望扩展变量,则必须在包含变量的字符串周围使用双引号,而不是单引号。

Difference between single and double quotes in Bash

所以这一行:

echo 'username:$password' | chpasswd

应该是:

echo "username:$password" | chpasswd

关于linux - bash shell 自动创建用户 - adduser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52160645/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com