exec program replaces the process of the script with the new
program, so should be used only where that makes sense. That is, the current script goes away and will not be able to run any subsequent commands (unless
exec program fails).
exec program as the last line of a shell script is useful where
program runs for long periods of time and you do not want a useless shell process dangling around in the process tree until
program exits. Use
pstree or other process tools to inspect the difference between:
exec sleep 9999
exec program is not at all useful if you want to run other shell commands after the
exec, as those shell commands are not reached (unless
To validate something after launch is actually fairly tricky, as
/usr/bin/java my-server will take time to launch (and Java can be excruciatingly slow in this regard; I recall one Java process that took upwards of 45 seconds to become available or shut itself down...) and depending on how busy the system is or the scheduler the validation process may run before or after the
my-server runs. As a kluge you can delay the validation step with something like
/usr/bin/java my-server &
exec /usr/bin/java my-validation
which gives 10 seconds for
my-server to launch itself, which may or may not be enough depending on how busy the system is and how long
my-server takes to start. Again, I've seen Java processes take upwards of 45 seconds to start, and that was not on a busy system where the startup time could be even longer. The
sleep may not be necessary if
my-validation is intelligent enough to wait for
my-server to get up and running.
It may make more sense to only start the server:
exec /usr/bin/java my-server
and do the validation that the service is running via a monitoring framework, elsewhere.
Yet another approach would be to integrate with
systemd or some other modern init framework that offers better process control than a shell script does. For example a process can communicate back to
systemd whether it has started properly, or
systemd can automatically restart the service under various conditions, and so forth.