是否可以将 if 语句放入管道中?

Is it possible to put if statement in a pipeline?

ps aux | grep node | grep -v grep | awk '{print }' | xargs kill -9

我使用上面的命令杀死所有 Node.js 进程 (Ubuntu) 但是如果没有节点进程 运行 它会显示错误 (stderr)。是否可以在管道中使用 if 语句来避免 xargs 什么也没收到?

类似于:

ps aux | grep node | grep -v grep | awk '{print }' | if [ $pip ] ; then
    xargs kill -9 $pip
fi

如果您在 Ubuntu,请查看 pkill。它应该负责整个管道。

pkill -9 node

man xargs:

   -r, --no-run-if-empty
          If the standard input does not contain any nonblanks,
          do not run the command.  Normally, the command is run
          once even if there is no input. This option is a GNU
          extension.

其他答案是正确的,可能解决了一个可能的 XY 问题,但没有回答问题的标题。

是的,可以在管道中使用 "if"。例如:

cd /tmp
touch a1 a2 a3
ls    # results a1 a2 a3 systemd-private...
ls | grep ^a | if grep a1; then echo yes; done

结果:

a1
yes

ls | grep ^a | if grep -e a1 -e a2; then echo yes; done  

产出

a1
a2
yes

这是怎么回事?管道正常执行,因为 "if" 运行它的条件。管道终止后,"if" 仍然存在,从其参数中获取退出结果,并执行要求执行的操作(这里,"echo yes",仅当 grep 确实找到一些匹配项时)。

进一步证明:

ls | grep ^a | if grep a4; then echo yes; done

结果没有任何打印,标准输出没有任何结果,更重要的是,没有执行 "echo yes"。

在某些情况下,这对于在处理结束时执行某些操作很有用,但我怀疑它是否还有很多其他用途。