How to get the PID of a recently started process in Bash
30,065
Solution 1
There are various ways:
- Let the script write its pid itself. Include line
echo $$ > /tmp/my.pid
in your script. - Use
pidof script_name
- 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)
Related videos on Youtube
Author by
Yuran Pereira
Updated on September 18, 2022Comments
-
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 itsPID
on the$PID
variable. But instead I keep getting the PID of "bash
" itself instead of the program I open which causes thekill -INT $PID
to just quit thescript.sh
while the xxx_program remains running. Note thexxx_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 almost 7 yearsShow us your actual script.
-
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 almost 7 yearsSince
$!
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 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 almost 7 yearsAs you say, "whatever you may think".
-
Yuran Pereira almost 7 years@muru PS: not trying to be rude tho. It just is what it is :p Peace
-
-
Yuran Pereira almost 7 yearsThanks a lot this worked great. "pidof" is definitely a better option compared to what I was doing
-
Hiran Chaudhuri about 2 yearsThe last line delivers two results: The pid of the grep is part of it.