【问题标题】:Is it possible to put if statement in a pipeline?是否可以将 if 语句放入管道中?
【发布时间】:2020-03-31 05:00:17
【问题描述】:
ps aux | grep node | grep -v grep | awk '{print $2}' | xargs kill -9

我使用上述命令杀死所有 Node.js 进程(Ubuntu),但如果没有节点进程正在运行,它将显示错误(stderr)。是否可以在管道中使用 if 语句来避免 xargs 收到任何内容?

类似:

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

【问题讨论】:

    标签: bash shell ubuntu pipe pipeline


    【解决方案1】:

    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.
    

    【讨论】:

    • 谢谢!但是假设我不使用 xargs,有没有一种通用的方法来做if...then?
    • 您可以执行echo foo | { x=$(cat); if [ "$x" ]; then echo "Contents: $x"; fi; } 之类的操作,但最好只捕获管道的输出并对其进行操作
    【解决方案2】:

    如果您使用的是 Ubuntu,请查看 pkill。它应该负责整个管道。

    pkill -9 node
    

    【讨论】:

      【解决方案3】:

      其他答案是正确的,可能解决了可能的 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
      是的

      和

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

      输出

      a1
      a2
      是的

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

      要进一步证明:

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

      没有打印任何内容,标准输出中没有任何内容,更重要的是,没有执行任何“echo yes”。

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

      【讨论】:

        猜你喜欢
        • 2021-05-07
        • 1970-01-01
        • 2022-11-24
        • 2017-01-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-18
        相关资源
        最近更新 更多