代码之家  ›  专栏  ›  技术社区  ›  kingmakerking

使用shell脚本确定是否存在unix用户名(多个)

  •  1
  • kingmakerking  · 技术社区  · 9 年前

    if id "alice" >/dev/null 2>&1; then
            echo "user exists"
    else
            echo "user does not exist"
    fi
    

    我想看看爱丽丝、鲍勃和卡罗尔是否存在。所以,当我在下面的代码中使用AND时,我可能会得到正确的结果,但它会从id命令中打印出不必要的行。

    if id "alice" && id "bob" && id "carol" >/dev/null 2>&1; then
            echo "user exists"
    else
            echo "user does not exist"
    fi
    

    输出如下:

    uid=1001(alice) gid=1002(alice) groups=1005(somegroupname),1002(alice)
    uid=1002(bob) gid=1003(bob) groups=1005(somegroupname),1003(bob)
    user exists
    

    <this_speicific_user> is not present.
    
    4 回复  |  直到 9 年前
        1
  •  2
  •   anubhava    9 年前

    可以使用大括号将所有3个命令分组为一个组:

    { id "alice" && id "bob" && id "carol"; } >/dev/null 2>&1
    
        2
  •  0
  •   P.P    9 年前

    您可以重定向每个命令的stderr:

    if id "alice" >/dev/null 2>&1 && id "bob" >/dev/null 2>&1 && id "carol" >/dev/null 2>&1;
    then
            echo "user exists"
    else
            echo "user does not exist"
    fi
    

    Oor使用复合命令:

    if { id "alice" && id "bob" && id "carol"; } >/dev/null 2>&1; then
            echo "user exists"
    else
            echo "user does not exist"
    fi
    
        3
  •  0
  •   Gaétan RYCKEBOER    9 年前

    || 就像你对 && :

    { test1 && test2 && test3 } || else_function
    

    { ! id "alice" && echo "alice absent." } || { ! id "bob" && echo "bob absent." } || { ! id "walter" && echo "walter absent." }
    

    甚至:

    absent=false
    for user in alice bob walter ; do
       ! id "$user" && echo "$user is absent." && absent=true
    done
    $absent || echo "All users are present."
    
        4
  •  0
  •   Erik Bennett    9 年前

    此外,如果你想测试它们,不管怎样,你都需要把它们分成单独的测试。否则,如果 id "alice"

    推荐文章