Check Whether a User Exists

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

    I like this nice one line solution

    getent passwd username > /dev/null 2&>1 && echo yes || echo no
    

    and in script:

    #!/bin/bash
    
    if [ "$1" != "" ]; then
            getent passwd $1 > /dev/null 2&>1 && (echo yes; exit 0) || (echo no; exit 2)
    else
            echo "missing username"
            exit -1
    fi
    

    use:

    [mrfish@yoda ~]$ ./u_exists.sh root
    yes
    [mrfish@yoda ~]$ echo $?
    0
    
    [mrfish@yoda ~]$ ./u_exists.sh
    missing username
    [mrfish@yoda ~]$ echo $?
    255
    
    [mrfish@yoda ~]$ ./u_exists.sh aaa
    no
    [mrfish@indegy ~]$ echo $?
    2
    

提交回复
热议问题