Getting the PID of a running command is something I do daily, particularly by grepping on the name, e.g.:
The second column gives the process ID, which I then pick out to do something with (e.g. send a signal). You can use awk to print just that column, like so:
However, typing out this command each time is a bit of a pain, so I created a bash script to give me the process ID given a grep string:
There are several things that this script gives you:
Argument handling - all arguments are passed to the first grep
Some flavours of Unix include the grep command in the process list, which is a pain - this script removes it
Exactly one PID is expected - if more than one process is found matching the pattern then the script fails and warns you
It also fails if no processes are found matching the pattern
I added this script to /usr/local/bin/findpid and made it executable. You can then use it like this:
Or to see the case where it fails:
You can also embed this in other commands, such as kill: