I have a bash function func_1 which calls func_2. func_2 does not terminate until told to via ^C. How can I terminate func_2 and then continue execution of func_1? Calling func_1 and then terminating during func_2 stops func_1. Thanks!
1 Answer
Assuming the processing in func_2 is done with external program (see sleep statement in example below), you can use 'trap' to capture the ctrl/C (actually SIGINT, as per comments above from @anishsane)
Note that explicit termination of the external process is performed by dispatching the signal to that child.
#! /bin/bash
func_1() {
echo "In func_1"
sleep 100 &
# Save the PID of the external program
X=$!
trap 'kill -INT $X' INT
# Wait for the external program to finish/get killed.
wait
echo "resume func_1"
}
func_2() {
echo "In func_2"
func_1
echo "resume func_2"
}
func_2
If you can the above script, and enter "ctrl/C", the output will be:
In func_2
In func_1
^Cresume func_1
resume func_2
func_2is doing from atrapor the surrounding code. If you include the actual code it would be easier to see what would actually work.^Cis equivalent ofSIGINT(i.e.kill -2).SIGTERMiskill -15.^C(SIGINT) are delivered at the process level. So, there is no way to terminate the current function without terminating the parent script. Having said that, you couldTRAPthe signals set some global variable and do an early exit fromfunc_2by detecting that variable. It will help us if you postfunc_2's code.