3

I have seen the following line in a bash script for killing a process(in this case started with the command loadgen):

ps xww | grep -i "loadgen" | grep "PATTERNMATCH_FACT.xml" | cut -c1-5 | xargs -i kill {} 2>/dev/null

I would like to understand the reason for piping after the two grep's in the command above.

The way the loadgen command is started is the following. It's a part of the startup script.

./loadgen -XMLFile ${DEMODIR}/bam-103-pattern-match/data/PATTERNMATCH_FACT.xml -duration 0 -frequency 2 
4

ps xww gives the following output

...
    1 ?        Ss     0:00 init [2]
 1804 pts/0    Ss     0:00 -bash
...

After the two grep's it pipes the output to cut. This command cuts the character 1-5 out of the output. In the output above it whould be the PID's:

    1
 1804

This is piped to xargs. Xargs builds commands that look like this:

kill 1
kill 1804

and executes them. 2>/dev/null means that all error messages are sent to the pseudo device /dev/null.

So your command kills every process that is greped out of the ps command.

Or see explainshell.

  • can you please explain the 2>/dev/null part? I don't get how errors are prevented. What errors are we talking about here? – Geek Dec 24 '13 at 17:49
  • Errors of shell commands are always written to channel 2. 2>/dev/null means that this channel is redirected to /dev/null, which is a pseudo device. Errors like when no process with the given PID is found. The 2>/dev/null part is not needed, its just cosmetics. – chaos Dec 24 '13 at 17:52
  • can you please explain the xargs -i kill {} part? Especially the {} part of it? Why is that needed? – Geek Dec 24 '13 at 18:04
  • 2
    xargs is a tool to expand its arguments into a commands list. Everything piped into xargs is considered a list to expand, and {} is the placeholder for 'list item here'. So sending to ... | xargs kill {} means "for every thing in this list, use the command kill _____, and fill in the blank with the list entry. – DopeGhoti Dec 24 '13 at 20:11
  • kill errors are not prevented. They happen as usual. 2>/dev/null just discards the actual error messages. – jfs Dec 24 '13 at 20:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.