Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have simple bash script

#!/bin/bash

(while true; do
        true;
        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.

like image 432
Sever Avatar asked Nov 28 '25 01:11

Sever


1 Answers

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.
26159

$ kill "$bgPID"
[1]+  Terminated              ( while true; do
    true; sleep 3;
done )
like image 170
Inian Avatar answered Nov 29 '25 16:11

Inian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!