Bash 尝试通过管道输出时出错:语法错误

Bash error when trying to pipe output: Syntax error

我有一个 bash 脚本 (test.sh),其中包含以下内容:

#!/bin/bash

npm test |& grep -v '[HPM]'

if [[ $? -ne 0 ]]; then
...

尝试在本地 运行 此脚本时出现此错误:

test.sh: line 3: syntax error near unexpected token `&'
test.sh: line 3: `npm test |& grep -v '[HPM]''

|& 语法使用的是非标准标记,bash 但不是所有 shell 都能识别。这样的构造通常称为 bashism。如果您的 shell 被无意中调用为非 bash shell,那么这是一个语法错误。您可以轻松地为此使用标准化构造:

npm test 2>&1 | grep -v '\[HPM\]' 

请注意,这是不寻常的。捕获 npm 的 stderr 似乎很奇怪,但也许你真的想检查 grep 是否打印任何行。确实没有必要显式检查 $?,您的代码通常会这样写:

if ! npm test 2>&1 | grep -v '\[HPM\]'; then
    : grep failed.  Do something 
fi

但是,这又显得很奇怪。 grep -v 如果不打印任何文本行,则将“失败”,否则将成功。也许您期望 $? 在您的原始代码中包含 npm 的退出状态,但事实并非如此。如果 grep 打印任何文本,$? 将为零,否则为非零。