简体   繁体   中英

How to create a bash script in Linux that checks if the user is local or not

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

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.

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

Try this.

#!/bin/sh
USER="userid"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM