繁体   English   中英

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

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

我正在尝试创建一个提示输入用户名的 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

尝试以下脚本:

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条件评估函数的退出代码以确定用户是否存在。

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

或者

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

尝试这个。

#!/bin/sh
USER="userid"

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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