Is it possible to call a function at the time of termination of a shell script. I have some daemon processes running in the background whose process id is stored inside an array. At the time of termination (for whatsoever reason) I want a cleanup function/handler to get called which kills all the daemon processes.
# want the below function to be called when the shell script terminates for whatsoever reason
purge () {
for pid in ${pids[@]}; do
kill -9 $pid
done
}
./daemon1 > a.txt 2>&1 & pids+=($!)
./daemon2 > b.txt 2>&1 & pids+=($!)
./daemon3 > c.txt 2>&1 & pids+=($!)
for pid in ${pids[@]}; do
echo "process: $pid"
done
You just need to do:
#!/bin/bash
purge () { ... }
trap purge EXIT
From man bash
about trap
builtin:
If a sigspec is EXIT (0) the command arg is executed on exit from the shell
Check:
LESS='+/^ +trap.*sigspec' man bash
With this proper solution, regardless the exit, the function will be executed.