简体   繁体   English

bash shell自动创建用户-adduser

[英]bash shell automatically creating user - adduser

I need to automatically create a user by reading lines of a file that contains username, home directory and full name. 我需要通过读取包含用户名,主目录和全名的文件的行来自动创建用户。

I am new to bash shell scripting and it is very confusing to me. 我是bash shell脚本的新手,这让我感到非常困惑。

There is something wrong with my adduser command. 我的adduser命令有问题。 It gives the error - adduser: Only one or two names allowed. 它给出了错误-adduser:仅允许使用一个或两个名称。

following is the full script - 以下是完整的脚本-

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

I am sure that this script is riddled with syntax errors. 我确信此脚本充满语法错误。 Please help. 请帮忙。 my brain is fried. 我的大脑炸了。

Always quote your variables unless you deliberately want to split the value into separate words. 除非您有意将值拆分为单独的单词,否则请始终引用变量。

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

Also, you have to use double quotes around strings containing variables, not single quotes, if you want the variables to be expanded. 此外,如果要扩展变量,则必须在包含变量的字符串周围使用双引号,而不是单引号。

Difference between single and double quotes in Bash Bash中单引号和双引号之间的区别

So this line: 所以这行:

echo 'username:$password' | chpasswd

should be: 应该:

echo "username:$password" | chpasswd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM