Bash store pid of command


I have a problem. I am trying to monitor a Java program. To do that I have a start/stop Bash script that looks like this:

 case $1 in
       echo $$ > /var/script/myprogram/;
       (cd /var/script/myprogram/test; mvn exec:java)
       kill $(cat;
       echo "usage: test {start|stop}" ;;
 exit 0

The problem is that the pid that I write in is not the pid number of the Java program, but the pid of the current Bash script. Is there a way to get the pid file of the started Java program and write that pid number to


There are many reasons not to do what you are doing, but…a simple solution is to simply exec the java process so that the two pids are the same:

   echo $$ > /var/script/myprogram/;
   cd /var/script/myprogram/test
   exec mvn exec:java

exec will cause the current process to replace itself with the mvn process, so $$ is the correct pid. Also, this cleans up the process table, since the startup script no longer exists as the parent of the mvn.

Note that this is atypical behavior for a startup script, since it will not exit until the mvn process exits, but since this is what your original script is doing, it seems…still bizarre.

Answered By – William Pursell

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published