How to get the PID of a recently started process in Bash

30,065

Solution 1

There are various ways:

  1. Let the script write its pid itself. Include line echo $$ > /tmp/my.pid in your script.
  2. Use pidof script_name
  3. Use ps -ef | grep script_name | tr -s ' ' | cut -d ' ' -f2

Solution 2

You could use

pidof xxx_program 

if that is the name of the process. (must be full process name how it was invoked, including any options or commandline paths)

Share:
30,065

Related videos on Youtube

Yuran Pereira
Author by

Yuran Pereira

Updated on September 18, 2022

Comments

  • Yuran Pereira
    Yuran Pereira over 1 year

    I have a bash script file that contains the following code script.sh

    ./xxx_program arguments &
    PID=$!
    echo $PID
    kill -INT $PID
    

    what I am trying to do is to start a program "xxx_program" and then store its PID on the $PID variable. But instead I keep getting the PID of "bash" itself instead of the program I open which causes the kill -INT $PID to just quit the script.sh while the xxx_program remains running. Note the xxx_program opens but I just get the wrong PID.

    I would like to know if there's a way to get the PID of xxx_program? Thanks in advance

    • muru
      muru almost 7 years
      Show us your actual script.
    • Yuran Pereira
      Yuran Pereira almost 7 years
      @muru the other parts of the script that I did not show are really irrelevant to solving the problem. The way I wrote it up, is the same way I have it structured on my original script with the exception of "xxx_program" this is because I will not be using this for only one specific program.
    • muru
      muru almost 7 years
      Since $! works fine for getting the PID of the last backgrounded command and has worked fine for decades, it is certainly a better option than pidof, pgrep or anything else. If it doesn't work for you, then no, the script is not the same way you wrote it.
    • Yuran Pereira
      Yuran Pereira almost 7 years
      @muru well, whatever you may think. Anyhow it's solved now. Perhaps pidof even though not the quickest, is somehow more reliable?... Anyway, thanks for the help.
    • muru
      muru almost 7 years
      As you say, "whatever you may think".
    • Yuran Pereira
      Yuran Pereira almost 7 years
      @muru PS: not trying to be rude tho. It just is what it is :p Peace
  • Yuran Pereira
    Yuran Pereira almost 7 years
    Thanks a lot this worked great. "pidof" is definitely a better option compared to what I was doing
  • Hiran Chaudhuri
    Hiran Chaudhuri about 2 years
    The last line delivers two results: The pid of the grep is part of it.