Recently we came to the need of writing a bash
script that needed periodically to check if a specific process, that was started by the script, had ended and restart it (something like watchdog
but with not so many features).
To achieve this, we used the one of the shell special parameters, the $!
. Like all other special parameters $!
may only be referenced and the user cannot make an assignment to it.
(
$!
) Expands to the process ID of the job most recently placed into the background, whether executed as an asynchronous command or using thebg
builtin command.From GNU.org: https://www.gnu.org/software/bash/manual/html_node/Special-Parameters.html#index-_0021-1
Example of Usage
In this example we wanted to get the PID
of the application called server
to be used later on in the script.
server & echo $!; #This will print the process ID of the 'server' application
This post is also available in: Αγγλικα