我正在编写一个脚本来在多个 Linux 服务器上添加用户。但首先我想检查提到的用户名是否已经存在于该特定服务器上。
EXISTS=`ssh xyz 'egrep "$username" /etc/passwd | cut -d':' -f1'`
这是我正在尝试的命令。但它没有给我我想要的输出..而是给我 passwd 文件中的所有用户名。 变量 EXISTS 应该只有那个用户名,否则它应该是空的。
最佳答案
在任何现代 Linux 系统上,您都有 getent
。因此,不要像这样检查,而是检查返回码(通过 $?
):
getent passwd $username &>/dev/null
(如果用户存在则返回 0,如果不存在则返回 2;联机帮助页中描述的其他错误代码)
(注意:这不是真正的 Java 问题,是吗?)
编辑 好的,完整代码...
ssh thehost getent passwd $username;
RC=$?;
# check for $RC here; if 0, the user exists; if not 0 it doesn't.
# Man getent for more details
请注意,另一种解决方案是尝试直接添加用户;如果用户已经存在或其他原因,命令将失败;再次在这里,man useradd,并检查可能的返回码。
关于linux - 存在 =`ssh xyz ' egrep "$username"/etc/passwd | cut -d' :' -f1' `命令不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27314074/