Home  >  Q&A  >  body text

linux - shell创建用户,报错“passwd: Unknown user name '}''.”

思路:
判断用户是否存在,标记flag
存在,修改用户密码
不存在,创建用户并修改密码


#!/bin/bash
#the script act on a batch of add user,username at the same password 
name="admin"
password="demo"
userList="cat /etc/passwd | awk -F ':' '{print $1}'"
flag=false
for name in $userList; do
    #statements
    flag=true
done
if [ $flag=true ]; then
    #change password
    echo "user exist"
else
    echo "create user admin"
    useradd /home/$name $name
fi
echo "change password to demo"
echo $password | passwd --stdin $name
echo "succeed"

输出如下:


实际:
用户不存在且没有创建成功

PHPzPHPz2741 days ago2378

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:56:01

    Wouldn’t it be more convenient to use the id command to determine?

    id admin >& /dev/null
    if [ $? -ne 0 ]
    then
    #不等于0,创建用户
        echo "create user admin"
        useradd -d /home/admin -m admin
    else
    #等于0说明用户已经存在
        echo "user exist"
    fi

    Note that your useradd specifies the home directory parameter, otherwise the execution will be unsuccessful.
    And to determine whether the user exists in /etc/passwd, you can also use:

    grep admin /etc/passwd >& /dev/null;echo $?
    

    See if it is equal to 0.

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 13:56:01

    The reason why your user should include the } symbol

    reply
    0
  • Cancelreply