Bash – How to stop a background process started in the same script, without exit the script

background-processbashshell-script

I have a program that takes a variable time to run (no more than two minutes), and to make it less odious, I put fortune messages.

 #!/bin/bash
 ...
 for i in $(seq 1 45); do sleep 3; echo; echo; fortune; done &
 ...

However, the program duration may vary (depending on factors that are irrelevant here) and need to stop the messages.

 #!/bin/bash
 ...
 for i in $(seq 1 45); do sleep 3; echo; echo; fortune; done &
 ...
 if [any-condition]; Then
      #script is over... Stop messages!!!
 fi
 ...
 if [any-condition]; Then
      #Stop messages... script continue execution
 fi
 ... Blah blah
 ...
 #script is over stop Messages!

So if I prepare 45 messages in periods of 3 seconds, the program may end soon but the messages still appear in the terminal, interfering with other work.

I try with command jobs, but there are no jobs in background. Try with command ps but can't found the messages task.

How to stop that fortune messages?

Best Answer

The simplest way is to use $!. That is the PID of the last process launched in the background (from man bash):

!

Expands to the process ID of the job most recently placed into the background, whether executed as an asynchronous command or using the bg builtin.

So, you could do something like:

for i in $(seq 1 45); do sleep 3; echo; echo; fortune; done &
pid=$!

[ main script here]

if [any-condition]; then
  kill $pid
fi

However, I can't help thinking this is a rather convoluted way of doing things. I could give you a more specific example if you showed your whole script, but why not something like:

long_process &
while ps -p $! >/dev/null; do sleep 3; echo; echo; fortune; done 

That would let you launch whatever process takes that long and will run fortune until it ends.

Related Question