简体   繁体   中英

Is it possible to put if statement in a pipeline?

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

I use the above command to kill all Node.js processes (Ubuntu) abut if there is no node process running it will show an error (stderr). Is it possible to use if statement in a pipeline to avoid having xargs to receive nothing?

Something like:

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

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.

If you're on Ubuntu, have a look at pkill . It should take care of the entire pipeline.

pkill -9 node

The other answers are correct and probably address a possible XY problem, but do not answer the title of the question.

Yes, it is possible to use "if" in a pipe. For example:

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

results in:

a1
yes

and

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

outputs

a1
a2
yes

What is going here? That the pipeline is executed normally, because the "if" runs its condition. After the pipeline is terminated, the "if" is still alive, gets the exit result from its argument, and does what is asked to do (here, "echo yes", only if grep did find some match).

To have a further proof:

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

results in nothing being printed, nothing from standard output and, more important, no "echo yes" has been executed.

This can be useful in order to do something at the end of processing, in some cases, but I doubt it can have many other uses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM