0

In my bash script, I have a function that does one certain task in an infinite loop. To allow for the next part of my code to run at the same time, I run it with myFunc &.

How can I kill this function, when the rest of my program is done?

4

There are several options. If this is your only background process then you can easily kill it with

kill %1

You can save the PID of the subshell:

myFunc &
myFunc_PID=$!
[...]
kill -HUP "$myFunc_PID"

You can also use

kill %myFunc

It makes sense to put the subshell killing in the EXIT handler:

trap 'kill %myFunc' EXIT

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.