Sofia
Sofia

Reputation: 456

Terminate function inside another function on Linux shell

I'm really new to shell scripts and I'm trying to figure out how to terminate a function that uses an infinite loop inside another function. The code more or less looks like this:

finish=1

function1() {
    function2&
    ...
    finish=0
}
function2() {
    while [ $finish==1 ] 
    do
    ...
    done
}

And the main part of the script callS only function1. Is there any other way to terminate function2 when function1 finishes? I also tried killing it by id, but couldn't make it work.

Upvotes: 2

Views: 78

Answers (1)

hek2mgl
hek2mgl

Reputation: 158200

A function call in bash will be executed in a subshell. You can store the pid of that subshell and kill it before function1 exits. Like this:

function1() {
    function2&
    pid=$!

    ...

    kill "$pid"
}

function2() {
    while true 
    do
        ...
    done
}

Upvotes: 4

Related Questions