Using awk to capture first line of a multiline output?
-
26-10-2019 - |
Question
I have this output, which is the PID of all processes running matching a grep for fcgi:
# ps ax | grep fcgi | cut -f1 -d' '
21065
21066
21067
21068
21069
21070
24801
I want to cut out the very first number (i.e. 21065) so I can pass it to the kill function to kill the parent process (the parent process is returned as the first PID).
Any ideas on how to do this?
Solution
Use:
to get the pid number
PARENT_PID=`ps ax | grep fcgi | cut -f1 -d' ' | head -1`
to directly kill:
kill `ps ax | grep fcgi | cut -f1 -d' ' | head -1`
OTHER TIPS
Don't use ps ax | grep...
to kill a process, if you can avoid it. See here
Instead use pidof
There is no need to jump through all the hoops of running ps
, grep
, cut
, head
, and kill
yourself. That's what pkill
is for.
pkill fcgi
Also see pgrep
for future reference.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow