How to test whether a user already exist on Linux?

How to test whether a user account, say linuxuser, already exist on Linux?

You may make use of id which tries to get user IDs.

The Bash code snippet is as follows.

user=hello
id -u $user >/dev/null 2>&1
if [ "$?" == "0" ]; then
  echo "user $user already exist."
else
  echo "user $user doesn't exist."
fi

Or a shorter one

userexist=true
[ "`id -u $user 2>/dev/null`" == "" ] && userexist=false

The $userexist variable will contains whether $user already exists.

Answered by Eric Z Ma.

Eric Z Ma

Eric is a father and systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

Leave a Reply

Your email address will not be published. Required fields are marked *