bash shell自动创建用户 - adduser

问题描述 投票:-1回答:1

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

我是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

我确信这个脚本充满了语法错误。请帮忙。我的大脑是炒的。

linux bash shell ubuntu
1个回答
3
投票

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

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
© www.soinside.com 2019 - 2024. All rights reserved.