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?
IOW, just like
$$
holds your PID,$!
has the PID of the most recently executed background command.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.which will only output PIDs of imapsync if they are children of your script.
imapsync has an option to set where its pid is written:
--pidfile : the file where imapsync pid is written.
How about putting imapsync in the background momentarily, getting the PID and then foregrounding it... Something like this: