15

Can any one tell me how to get the PID of a command executed in bash.

E.g. I have a bash script that runs imapsync.

When the script is killed the imapsync process does not always get killed, so I'd like to be able to identify the PID of imapsync programatically from my script, so that I can kill the imapsync process myself in a signal handler.

So how do I programatically get the PID of a child process from a parent bash script?

Dave M
  • 4,494
Jason Tan
  • 2,792

4 Answers4

47
any_command args &
my_child_PID=$!

IOW, just like $$ holds your PID, $! has the PID of the most recently executed background command.

Javier
  • 9,486
10

Unlike pidof, pgrep can be given a variety of options to restrict which processes it returns PIDs for. One that may be particularly useful is to select based on PPID using the PID of the current process.

pgrep -P $$ imapsync

which will only output PIDs of imapsync if they are children of your script.

4

imapsync has an option to set where its pid is written:

--pidfile : the file where imapsync pid is written.

0

How about putting imapsync in the background momentarily, getting the PID and then foregrounding it... Something like this:

imapsync &
pid=$!
wait $pid
retVal=$?
Mark
  • 1