Check Whether a User Exists

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

    You can also check user by id command.

    id -u name gives you the id of that user. if the user doesn't exist, you got command return value ($?)1

    And as other answers pointed out: if all you want is just to check if the user exists, use if with id directly, as if already checks for the exit code. There's no need to fiddle with strings, [, $? or $():

    if id "$1" &>/dev/null; then
        echo 'user found'
    else
        echo 'user not found'
    fi
    

    (no need to use -u as you're discarding the output anyway)

    Also, if you turn this snippet into a function or script, I suggest you also set your exit code appropriately:

    #!/bin/bash
    user_exists(){ id "$1" &>/dev/null; } # silent, it just sets the exit code
    if user_exists "$1"; code=$?; then  # use the function, save the code
        echo 'user found'
    else
        echo 'user not found' >&2  # error messages should go to stderr
    fi
    exit $code  # set the exit code, ultimately the same set by `id`
    

提交回复
热议问题