Search code examples
linuxbashshellpstree

get the pid of specified process name from pstree by using shell script


I am using pstree to get a set of process and the result will be like

processA(123)---processB(124)---processC(125)---processTarget(126)---processD(127)

I would like to use the keyword "processTarget" to get the pid, that is 126.

The reason why i chose the pstree is that I will send SIGTSTP signal and SIGCONT to this set of process.

How could I do that? Is there any easy to do it?

Note:The processTarget(126) is not in the fixed position, therefore I could not use awk to get the PID.


Solution

  • You can use grep.

    <pstree command> | grep -P -o 'processTarget\([0-9]+\)'

    -P means use Perl regex -o mean only return the match

    man grep for more details

    If the goal is to get just the id you can continue this approach to return just the integer

    <pstree command> | grep -P -o 'processTarget\([0-9]+\)' | grep -P -o '[0-9]+'