ps x -o pid=,command= | grep -E "^[0-9]+ INSERT_PROCESS_NAME" | grep -o -E [0-9]+
eg:
ps x -o pid=,command= | grep -E "^[0-9]+ lighttpd" | grep -o -E [0-9]+
Actually this is better
ps x -o pid=,command= | grep -E ^[0-9]+[[:blank:]]lighttpd | grep -o -E [0-9]+
In this format it can be used easily in an ANT build file or similar to find a process that you may need to kill:
<!-- lighttpd search and destroy functions --> <target name="lighttpd.search"> <exec executable="sh" outputproperty="lighttpd.pid" > <arg line="-c 'ps x -o pid=,command= | grep -E ^[0-9]+[[:blank:]]lighttpd | grep -o -E [0-9]+'" /> </exec> </target> <target name="lighttpd.destroy" if="lighttpd.pid"> <exec executable="kill"> <arg line="${lighttpd.pid}" /> </exec> </target>
In the specific case of lighttpd and ANT
The regular expression lighttpd[[:blank:]]-f
works better as it works regardless of the path in which lighttpd is run from. Which is good as it saves escaping slashes in the regex…
One last Update
Courtesy of the shellwise @neotrophy here is an implementation that uses cut
instead of grep
:
ps x -o pid=,command= | grep -E lighttpd[[:blank:]]-f | cut -d \ -f1
Additionally, he suggested implementations of awk
and sed
that were probably a little nicer, but I’m happy enough with the above - especially given it’s working and I’m killing lighttpd processes from ant now :)