Check if user exists

Asked

Viewed 1,179 times

2

How can I in bash check if a user exists, but in such a way that script work in multiple systems ?

A limited example:

grep <username> /etc/passwd

Does not work on systems that use NIS or LDAP to manage users.

1 answer

2


The command getent should work in this case.

getent passwd <usuario>

The command getent displays database entries supported by Service Switch, which are configured in the file /etc/nsswitch.conf.

Another alternative that may work in this case is to check whether the ID user is valid through the command id, using with the option -u:

if id -u "usuario" > /dev/null 2>&1; then
        echo "Utilizador existe"
else
        echo "O utilizador especificado não existe"
fi
  • 1

    I ended up solving the problem with the command id which already seems to be compatible with multiple user management systems.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.