José Peralta José Peralta - 7 months ago 10
Bash Question

How to capture a process Id and also add a trigger when that process finishes in a bash script?

I am trying to make a bash script to start a jar file and do it in the background. For that reason I'm using

. Right now I can capture the pid of the java process but I also need to be able to execute a command when the process finishes.

This is how I started

nohup java -jar jarfile.jar & echo $! > conf/pid

I also know from this answer that using
will make a command execute after the first one finishes.

nohup java -jar jarfile.jar; echo "done"

echo "done"
is just an example. My problem now is that I don't know how to combine them both. If I run
echo $!
first then
echo "done"
executes immediately. While if
echo "done"
goes first then
echo $!
will capture the PID of
echo "done"
instead of the one of the jarfile.

I know that I could achieve the desire functionality by polling until I don't see the PID running anymore. But I would like to avoid that as much as possible.


You can use the bash util wait once you start the process using nohup

nohup java -jar jarfile.jar &
pid=$!     # Getting the process id of the last command executed

wait $pid  # Waits until the process mentioned by the pid is complete
echo "Done, execute the new command"