Issue
I'm trying to create a Linux bash script that prompts for a username. For example, it asks for a username, once the username it's typed it will check if the user exists or not. I already tried to do it, but I'm not sure if I did it correctly. I would appreciate your help.
Here is how I did it:
#!/bin/bash
echo "Enter your username:"
read username
if [ $(getent passwd $username) ] ; then
echo "The user $username is a local user."
else
echo "The user $username is not a local user."
fi
Solution
if grep -q "^${username}:" /etc/passwd; then
echo "yes the user '$username' exists locally"
fi
OR
getent
command is designed to gather entries for the databases that can be backed by /etc files and various remote services like LDAP, AD, NIS/Yellow Pages, DNS and the likes.
if getent passwd "$username" > /dev/null 2>&1; then
echo "yes the user '$username' exists either local or remote"
fi
Will do your job, for example below
#!/bin/bash
echo "Enter your username:"
read username
if getent passwd "$username" > /dev/null 2>&1; then
echo "yes the user '$username' exists either local or remote"
else
echo "No, the user '$username' does not exist"
fi
Answered By - Akshay Hegde Answer Checked By - Mildred Charles (WPSolving Admin)