Don
Don

Reputation: 235

How to kill a running bash function from terminal?

...... (some awesome script).............
echo "I just wanna kill the function, not this"
myFunction()
{
while true
do
echo "this is looping forever"
done
}
myFunction
...... (some awesome script)...............

How to kill a running function without killing the script itself from terminal ?

Upvotes: 3

Views: 1503

Answers (1)

nlu
nlu

Reputation: 1963

First you cannot "kill" a function, "killing" refers to processes.

However you can install some special signal handling inside your function, that can make it react the way you want.

For this in bash you use trap, to define a signal handler for the signal you want to catch.

The function that is used as a signal handler here, also clears the trap, as traps are global and the defined handler would be called on any subsequent SIGUSR1 that could occur.

echo "I just wanna kill the function, not this"
trap_myFunction()
{
    trap - SIGUSR1
    return
}


myFunction()
{
    trap trap_myFunction SIGUSR1
    while true
    do
        echo "this is looping forever"
        sleep 1
    done
}
myFunction

echo "Continuing processing .."

Now, if you start this script and kill it, using:

kill -SIGUSR1 pid_of_process

it will enter the signal handler installed, which is simply return and continue with the echo-command after myFunction.

If you kill it by using any other signal, the trap will not be triggered and the process will be terminated completely.

Upvotes: 5

Related Questions