linuxbashcommand-linegrep

Getting Process ID Linux using pgrep


I have a bash script called run.sh which launches two python scripts meter_1.py and meter_2.py

#!/bin/sh

./meter_1.py &
./meter_2.py &

When the scripts are running and I search for the PID of the scripts using the command

ps -aux | grep python

The output is

openhab+  9328 84.0  1.6  25320 16580 pts/0    R    22:23   0:04 python ./meter_1.py
openhab+  9329 84.6  1.6  25320 16596 pts/0    R    22:23   0:04 python ./meter_2.py

Using the pgrep command I can get the the PID

>pgrep python 
9328 
9329 

However I could have multiple python scripts running and I want to get the process ID name by the script it is running not based on if it is python or not.

For example:

>pgrep python" "./meter_1.py
9328 

Is there a functionality for this in pgrep? The following seems to work however it would be nice to get just the process ID back.

>ps -aux | grep python" "./meter_1.py
openhab+  9328 84.0  1.6  25320 16580 pts/0    R    22:23   0:04 python ./meter_1.py

Solution

  • In ba(sh) you can get the PID of the last started process with $!

    so in your run.sh script you can simply use:

    #!/bin/sh
    
    ./meter_1.py &
    echo PID of process1: $!
    ./meter_2.py &
    echo PID of process2: $!