Sever Sever - 1 year ago 131
Linux Question

PID of infinite loop run in background (&) in bash script

I have simple bash script


(while true; do
sleep 3
done) &

How can I assign pid of this loop to variable, to kill process in future ? I try trap, but loop has own pid so I should know pid of loop running in background to kill it for example after SIGTERM.

Answer Source

The PID of the background-process started can be extracted from this $! variable.

$ (while true; do
>         true;
>         sleep 3
> done) &
[1] 26159

$ bgPID=$!; echo "$bgPID"         # <---- To store it in a bash variable.

$ kill "$bgPID"
[1]+  Terminated              ( while true; do
    true; sleep 3;
done )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download