我想在cat /etc/passwd | grep“sysa”不为真时执行echo命令。

我做错了什么?

if ! [ $(cat /etc/passwd | grep "sysa") ]; then
        echo "ERROR - The user sysa could not be looked up"
        exit 2
fi

当前回答

我做错了什么?

$(…)保存的是值,而不是退出状态,这就是为什么这种方法是错误的。然而,在这个特定的情况下,它确实可以工作,因为将打印sysa,从而使测试语句成为现实。然而,如果![$(true)];再回声虚假;fi将总是打印false,因为true命令不会向stdout写入任何内容(即使退出码为0)。这就是为什么它需要被改写为if !grep…;然后。

另一种方法是cat /etc/passwd | grep "sysa" ||回声错误。编辑:正如Alex指出的,cat在这里是无用的:grep "sysa" /etc/passwd ||回声错误。

发现其他答案相当混乱,希望这能帮助到一些人。

其他回答

我希望在答案中看到直接使用grep和-q选项(因为我们不关心结果,但只需要返回代码)。

if ! grep -qs "sysa" /etc/passwd; then
        echo "ERROR - The user sysa could not be looked up" >&2
        exit 2
fi

或(在失败时使用链式执行)

grep -qs "sysa" /etc/passwd || {
        echo "ERROR - The user sysa could not be looked up" >&2
        exit 2
}

更好的是,因为需要相反的东西,所以有选项-v

if grep -qsv "sysa" /etc/passwd; then
        echo "ERROR - The user sysa could not be looked up" >&2
        exit 2
fi

或者(在成功时使用链式执行)

grep -qsv "sysa" /etc/passwd && {
        echo "ERROR - The user sysa could not be looked up" >&2
        exit 2
}

笔记

我喜欢将错误消息重定向到stderr,但回显输出到stdout,因此>&2 泰勒搜索模式,例如'^sysa:'如果它是完全登录。

简单:

if ! examplecommand arg1 arg2 ...; then
    #code block
fi

没有括号。

这一个

if [[ !  $(cat /etc/passwd | grep "sysa") ]]; then
  echo " something"
  exit 2
fi

下面是一个例子:

为了确保数据记录器在线,cron脚本每15分钟运行一次,如下所示:

#!/bin/bash
#
if ! ping -c 1 SOLAR &>/dev/null
then
  echo "SUBJECT:  SOLAR is not responding to ping" | ssmtp abc@def.com
  echo "SOLAR is not responding to ping" | ssmtp 4151112222@txt.att.com
else
  echo "SOLAR is up"
fi
#
if ! ping -c 1 OUTSIDE &>/dev/null
then
  echo "SUBJECT:  OUTSIDE is not responding to ping" | ssmtp abc@def.com
  echo "OUTSIDE is not responding to ping" | ssmtp 4151112222@txt.att.com
else
  echo "OUTSIDE is up"
fi
#

...你可以在蒙太奇中看到的每一个数据记录器 在http://www.SDsolarBlog.com/montage


供参考,使用&>/dev/null将命令的所有输出(包括错误)重定向到/dev/null

(条件只要求ping命令的退出状态)

另外,请注意,由于cron作业以root身份运行,因此不需要在cron脚本中使用sudo ping。

在支持它的Unix系统上(似乎不是macOS):

if getent passwd "$username" >/dev/null; then
    printf 'User %s exists\n' "$username"
else
    printf 'User %s does not exist\n' "$username"
fi 

这样做的好处是,它将查询可能正在使用的任何目录服务(YP/NIS或LDAP等)和本地密码数据库文件。


grep -q "$username" /etc/passwd的问题是,当没有这样的用户时,它会给出一个错误的阳性结果,但其他用户与模式匹配。如果文件中的其他地方有部分或完全匹配,就会发生这种情况。

例如,在我的passwd文件中,有一行写着

build:*:21:21:base and xenocara build:/var/empty:/bin/ksh

这将在cara和enoc等上引发有效的匹配,即使我的系统上没有这样的用户。

要正确使用grep解决方案,您需要正确解析/etc/passwd文件:

if cut -d ':' -f 1 /etc/passwd | grep -qxF "$username"; then
    # found
else
    # not found
fi

... 或针对:分隔字段的第一个字段的任何其他类似测试。