如何在bash脚本中添加Unix / Linux用户


9

这是我的测试bash脚本。我无法使其正常工作。我看到两个错误:

  1. Use of uninitialized value $answer in chop at /usr/sbin/adduser line 589.
  2. Use of uninitialized value $answer in pattern match (m//) at /usr/sbin/adduser line 590.

这是我的脚本:

#!/bin/bash
sudo adduser myuser << ENDX
password
password
First Last




Y
ENDX
exit 0

这是输出:

me@mycomputer$ ./adduser.sh 
Adding user `myuser' ...
Adding new group `myuser' (1001) ...
Adding new user `myuser' (1001) with group `myuser' ...
Creating home directory `/home/myuser' ...
Copying files from `/etc/skel' ...
Enter new UNIX password: Retype new UNIX password: passwd: password updated successfully
Changing the user information for myuser
Enter the new value, or press ENTER for the default
        Full Name []:   Room Number []:         Work Phone []:  Home Phone []:  Other []: Use of uninitialized value $answer in chop at /usr/sbin/adduser line 589.
Use of uninitialized value $answer in pattern match (m//) at /usr/sbin/adduser line 590.
Is the information correct? [Y/n] me@mycomputer$

这是在Kubuntu 12.04 LTS上

$ bash --version
bash --version
GNU bash, version 4.2.25(1)-release (x86_64-pc-linux-gnu)

这是来自adduser的行(系统脚本-我未修改),带有两个相关行号的表示法:

for (;;) {
       my $chfn = &which('chfn');
    &systemcall($chfn, $new_name);
    # Translators: [y/N] has to be replaced by values defined in your
    # locale.  You can see by running "locale yesexpr" which regular
    # expression will be checked to find positive answer.
    print (gtx("Is the information correct? [Y/n] "));
    chop (my $answer=<STDIN>);        <-- LINE 589
    last if ($answer !~ m/$noexpr/o); <-- LINE 590
}

Answers:


31

只需使用命令行参数代替stdin,并使用chpasswd作为密码。

例如:

sudo adduser myuser --gecos "First Last,RoomNumber,WorkPhone,HomePhone" --disabled-password
echo "myuser:password" | sudo chpasswd

2

adduser调用外部程序chfn以读取全名和其他用户信息。chfn读取缓冲输入,不仅包括所需内容,还包括最后Y一行。当adduser确认之后询问,该Y行已被读取(但忽略)的chfn,所以adduser看到的文件在其输入结束。该变量$answer应包含一行输入,但是由于没有要读取的输入,因此未定义。

由于您正在编写脚本,因此请在命令行上传递数据(密码除外)

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.