Reputation: 33
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
Upvotes: 2
Views: 4003
Reputation: 16997
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
Upvotes: -1
Reputation: 179
Try this.
#!/bin/sh
USER="userid"
if id $USER > /dev/null 2>&1; then
echo "user exist!"
else
echo "user deosn't exist"
fi
Upvotes: -1
Reputation: 5062
Try the following script :
user="bob"
if cut -d: -f1 /etc/passwd | grep -w "$user"; then
echo "user $user found"
else
echo "user $user not found"
fi
The file /etc/passwd
contains a list of the local users along with some parameters for them. We use cut -d: -f1
to only extract the usernames, and match it with our user with grep -w $user
. The if
condition evaluate the exit code of the function to determine if the user is present.
Upvotes: 2