2

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.

Sever
  • 2,338
  • 5
  • 35
  • 55
  • You could try to do `ps -eaf | grep "bash"` to find the process. But this will typically give you a list of more than one process. In which case it becomes guesswork. @redneb's answer is cooler. – Chem-man17 Sep 22 '16 at 08:49

2 Answers2

6

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 )
Inian
  • 80,270
  • 14
  • 142
  • 161
3

You can write the pid to a file. Then read that file when you need it. For example you could do something like:

#!/bin/bash

(bash -c 'echo $PPID' > /tmp/myprocess.pid
 while true; do
        true;
        sleep 3
done) &

Then if you would like to kill the background process you would run something like:

kill $(</tmp/myprocess.pid)

See also.

redneb
  • 21,794
  • 6
  • 42
  • 54