X

Check if Linux user exists using Bash script

Here I will show you how to check if a Linux user exists (or does not exist) in a POSIX-compatible shell like Bash or Dash. I will use the getent command along with the /etc/passwd file for this.

Example Bash script:

if getent passwd "$username" >/dev/null; then
  echo "User $username exists"
else
  echo "User $username does not exist"
fi

Replace the variable $username with the name of the user you want to check.

If you want to check if a username does not exist, you can negate the result of getent command like this:

if ! getent passwd "$username" >/dev/null; then
  echo "User $username does not exist"
fi

The ! operator in front of the getent command is used to negate the exit code and the if statement then checks the negated exit code.

Till Brehm:
X

Headline

You can control the ways in which we improve and personalize your experience. Please choose whether you wish to allow the following:

Privacy Settings