2

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
shabam
  • 33
  • 1
  • 6
  • `getent` will check network logins as well, so this test probably won't be what you want – Eric Renouf Mar 14 '17 at 17:19
  • At this point, it's all about testing, right. What happens if you user your userID? Does that work, good. What happens if you use something you're sure doesn't exist on your system, maybe `nonesuch` or `ThereIsNoWayThisIsAUserName` or ?? You may also consider looking in `/etc/passwd` to confirm user is "local", but that can vary depending on who/what is responsible for your computing environment. (School, corp, etc, `passwd` file is probably not trustworthy). Good luck. – shellter Mar 14 '17 at 17:21
  • I'm voting to close this question as off-topic because Stack Overflow is for finding solutions to coding problems. For advice on improving working code, please use [codereview.se] instead. – Toby Speight Mar 14 '17 at 18:18
  • What is a local user, what is a non-local user in your scenario? – jhscheer Mar 14 '17 at 19:59

3 Answers3

1

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.

Aserre
  • 4,916
  • 5
  • 33
  • 56
0
if id "$username" >/dev/null 2>&1; then
      echo "yes the user '$username' exists"
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"
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"
else
    echo "No, the user '$username' does not exist"
fi
Akshay Hegde
  • 16,536
  • 2
  • 22
  • 36
0

Try this.

#!/bin/sh
USER="userid"

if id $USER > /dev/null 2>&1; then
   echo "user exist!"
else
  echo "user deosn't exist"
fi
kenessa
  • 181
  • 1
  • 3