Check Whether a User Exists

后端 未结 17 1907
清歌不尽
清歌不尽 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:57

    Using sed:

    username="alice"
    if [ `sed -n "/^$username/p" /etc/passwd` ]
    then
        echo "User [$username] already exists"
    else
        echo "User [$username] doesn't exist"
    fi
    
    0 讨论(0)
  • 2020-11-29 17:58

    By far the simplest solution:

    if id -u "$user" >/dev/null 2>&1; then
        echo 'user exists'
    else
        echo 'user missing'
    fi
    

    The >/dev/null 2>&1 can be shortened to &>/dev/null in Bash.

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

    Actually I cannot reproduce the problem. The script as written in the question works fine, except for the case where $1 is empty.

    However, there is a problem in the script related to redirection of stderr. Although the two forms &> and >& exist, in your case you want to use >&. You already redirected stdout, that's why the form &> does not work. You can easily verify it this way:

    getent /etc/passwd username >/dev/null 2&>1
    ls
    

    You will see a file named 1 in the current directory. You want to use 2>&1 instead, or use this:

    getent /etc/passwd username &>/dev/null
    

    This also redirects stdout and stderr to /dev/null.

    Warning Redirecting stderr to /dev/null might not be such a good idea. When things go wrong, you will have no clue why.

    0 讨论(0)
  • 2020-11-29 18:02

    This is what I ended up doing in a Freeswitch bash startup script:

    # Check if user exists
    if ! id -u $FS_USER > /dev/null 2>&1; then
        echo "The user does not exist; execute below commands to crate and try again:"
        echo "  root@sh1:~# adduser --home /usr/local/freeswitch/ --shell /bin/false --no-create-home --ingroup daemon --disabled-password --disabled-login $FS_USER"
        echo "  ..."
        echo "  root@sh1:~# chown freeswitch:daemon /usr/local/freeswitch/ -R"
        exit 1
    fi
    
    0 讨论(0)
  • 2020-11-29 18:02

    I was using it in that way:

    if [ $(getent passwd $user) ] ; then
            echo user $user exists
    else
            echo user $user doesn\'t exists
    fi
    
    0 讨论(0)
提交回复
热议问题