linux - 存在 =`ssh xyz ' egrep "$username"/etc/passwd | cut -d' :' -f1' `命令不能正常工作

标签 linux bash ssh

我正在编写一个脚本来在多个 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/

相关文章:

regex - AWK 正则表达式中的行尾符号

qt - Qt中如何轻松建立SSH连接?

c - 从 CSV 文件中检索值

linux - 安装arch后无法上网

c - 从不断更新的文件中读取

linux - 如何在 Haproxy 后面添加/删除新服务器且中断最少

linux - bash 选择命令

python - 无法在终端 "bash:/etc/odbcinst.ini: Permission denied"中回显

jenkins - 通过 socks 代理连接到Jenkins Node

tensorflow - 从 PC 的控制台使用 ssh 连接到 google collab