2017-03-14 48 views
1

我试图创建一个提示输入用户名的Linux bash脚本。例如,它要求输入用户名,一旦输入用户名,它将检查用户是否存在。我已经尝试过,但我不确定自己是否做得对。 我将不胜感激您的帮助。如何在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 
+0

'getent'会检查网络登录一样,所以这个测试可能不会是你想要的 –

+0

在这一点上,它是所有关于测试,对。如果你使用你的用户ID会发生什么?这是否有效,很好。如果你使用你确定不存在于系统中的东西,可能是'nonesuch'或'ThereIsNoWayThisIsAUserName'或??您也可以考虑查看'/ etc/passwd'来确认用户是否是“本地”,但这可能会因您的计算环境的责任而有所不同。 (学校,公司等,'passwd'文件可能不可信)。祝你好运。 – shellter

+0

我正在投票关闭这个问题作为题外话,因为堆栈溢出是为了找到编码问题的解决方案。有关改进工作代码的建议,请改为使用[codereview.se]。 –

回答

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

+2

嗯,我的用户'bobo'被发现,但我没有'bob' –

+0

@EricRenouf你是绝对正确的,我必须调整grep标志来强制完全匹配 – Aserre

相关问题