Check Whether a User Exists

后端 未结 17 1906
清歌不尽
清歌不尽 2020-11-29 17:31

I want to create a script to check whether a user exists. I am using the logic below:

# getent passwd test > /dev/null 2&>1
# echo $?
0
# getent pa         


        
相关标签:
17条回答
  • 2020-11-29 17:47

    user infomation is stored in /etc/passwd, so you can use "grep 'usename' /etc/passwd" to check if the username exist. meanwhile you can use "id" shell command, it will print the user id and group id, if the user does not exist, it will print "no such user" message.

    0 讨论(0)
  • 2020-11-29 17:47

    Login to the server. grep "username" /etc/passwd This will display the user details if present.

    0 讨论(0)
  • 2020-11-29 17:48

    There's no need to check the exit code explicitly. Try

    if getent passwd $1 > /dev/null 2>&1; then
        echo "yes the user exists"
    else
        echo "No, the user does not exist"
    fi
    

    If that doesn't work, there is something wrong with your getent, or you have more users defined than you think.

    0 讨论(0)
  • 2020-11-29 17:53

    Why don't you simply use

    grep -c '^username:' /etc/passwd
    

    It will return 1 (since a user has max. 1 entry) if the user exists and 0 if it doesn't.

    0 讨论(0)
  • 2020-11-29 17:56

    I suggest to use id command as it tests valid user existence wrt passwd file entry which is not necessary means the same:

    if [ `id -u $USER_TO_CHECK 2>/dev/null || echo -1` -ge 0 ]; then 
    echo FOUND
    fi
    

    Note: 0 is root uid.

    0 讨论(0)
  • 2020-11-29 17:56

    Depending on your shell implementation (e.g. Busybox vs. grown-up) the [ operator might start a process, changing $?.

    Try

    getent passwd $1 > /dev/null 2&>1
    RES=$?
    
    if [ $RES -eq 0 ]; then
        echo "yes the user exists"
    else
        echo "No, the user does not exist"
    fi
    
    0 讨论(0)
提交回复
热议问题