如何在Linux中创建一个bash脚本来检查用户是否是本地用户

时间:2017-03-14 17:15:57

标签: linux bash shell

我正在尝试创建一个提示输入用户名的Linux bash脚本。例如,它要求输入用户名,一旦输入用户名,它将检查用户是否存在。我已经尝试过这样做了,但我不确定我是否做得对。 我很感激你的帮助。

我是这样做的:

    #!/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

3 个答案:

答案 0 :(得分:1)

尝试以下脚本:

user="bob"
if cut -d: -f1 /etc/passwd | grep -w "$user"; then
    echo "user $user found"
else
    echo "user $user not found"
fi

文件/etc/passwd包含本地用户的列表以及它们的一些参数。我们使用cut -d: -f1仅提取用户名,并将其与grep -w $user的用户匹配。 if条件评估函数的退出代码以确定用户是否在场。

答案 1 :(得分:0)

if id "$username" >/dev/null 2>&1; then
      echo "yes the user '$username' exists"
fi

OR

getent命令用于收集可由/ etc文件和各种远程服务(如LDAP,AD,NIS /黄页,DNS等)支持的数据库条目。

if getent passwd "$username" > /dev/null 2>&1; then
    echo "yes the user '$username' exists"
fi

将完成你的工作,例如下面的

#!/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

答案 2 :(得分:0)

尝试一下。

#!/bin/sh
USER="userid"

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