Imdad Imdad - 16 days ago 6
Bash Question

shell script gives output in 2 lines I need only 1

I have the following commands saved in a .sh file

prog=$1
ps axf | grep $prog | grep -v grep | awk '{print "kill -9 " $1}'


I get the following output when I execute it

kill -9 3184
kill -9 20359


But I just need the first line of it as that is the only valid pid. How can I remove the 2nd line from the output.

Answer

There are a few issues with what you want to do:

  • You're building a chain of 4 commands for something relatively simple
  • You're going to get as a result only the first line of a list of processes containing $prog (excluding the grep $prog which you filtered out); how can you be sure that's the process you want?

The correct command to use is

pkill $prog`

as suggested in the comments, which probably will do what you want.

Just for information, and to answer your question, you can pipe an output to head -n 1 to return only the first line:

<list of commands> | head -n 1

However, in your case this would add a fifth command to the chain, so I recommend you don't do it this way.