Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the process ID in a Shell script when a process is launched in foreground

Tags:

linux

shell

In a shell program I want to launch a program and get its PID and save in a temp file. But here I will launch the program in the foreground and will not exit the shell until the process is in running state

ex:

 #!/bin/bash

 myprogram &
 echo "$!"  > /tmp/pid

And this works fine i am able to get the pid of the launched process . But if i launch the program in fore ground i want to know how to get the pid

ex :

#!/bin/bash

myprogram       /// hear some how i wan to know the PID before going to next line
like image 301
Naggappan Ramukannan Avatar asked Aug 30 '13 14:08

Naggappan Ramukannan


1 Answers

As I commented above since your command is still running in foreground you cannot enter a new command in the same shell and goto the next line.

However while this command is running and you want to get the process id of this program from a different shell tab/window process then use pgrep like this:

pgrep -f "myprogram"
17113 # this # will be different for you :P

EDIT: Base on your comment or is it possible to launch the program in background and get the process ID and then wait the script till that process gets exited ?

Yes that can be done using wait pid command as follows:

myprogram &
mypid=$!
# do some other stuff and then
wait $mypid
like image 83
anubhava Avatar answered Sep 30 '22 02:09

anubhava