Home > Blockchain >  How to do ps pipelines with linux?
How to do ps pipelines with linux?

Time:05-07

I tried pipelines like

ps -A | grep "smthn" | kill -4 (smthn's PID)

So how can i grab multiple processes PID's from grep output? Like ps -A | grep "smthn", "smthn1", "smthn2" | kill -4 (smthn's PID)

CodePudding user response:

I don't think kill reads from stdin, it only takes pids as arguments. So use kill $(...) instead, where the code to find the pids replaces the dots in the $(...) part.

To find the pids:

ps -A | grep smthn | grep -v grep | cut -d " " -f 1

Here the first grep looks for smthn, the second grep filters out the grep command that is looking for smthn and is still running at this time. Then cut picks just the first field of the output, which is the pid.

Put together:

kill -4 $(ps -A | grep smthn | grep -v grep | cut -d " " -f 1)

If you have pgrep and pkill and the process is always named the same (always smthn, not smthn1, smthn2, and so on), you can simplify this a lot. pgrep just returns the pid, so you don't need to work with grep -v and cut:

kill -4 $(pgrep smthn)

pkill just sends the signal to whatever process executable you specify:

pkill -4 smthn
  • Related