Using traps inside a function

If we use the trap command inside a function in the script, then the reassigned signal behavior will become global inside a script. We can check this effect in the following script example.

Let's write shell script trap_01.sh as follows:

#!/bin/bash 
trap "echo  caught signal SIGINT" SIGINT 
trap "echo  caught signal SIGQUIT" 3 
trap "echo  caught signal SIGTERM" 15 
while : 
do 
    sleep 50 
done 

Let's test the program as follows:

    $ chmod +x trap_01.sh
    $ ./trap_01.sh

Output:

    ^Ccaught signal SIGINT
    ^Quit (core dumped)
    caught signal SIGQUIT

Let's write one more trap_02.sh shell script as follows:

#!/bin/bash trap "echo caught signal SIGINT" SIGINT trap "echo caught signal SIGQUIT" 3 trap "echo caught signal SIGTERM" 15 ...

Get Learning Linux Shell Scripting - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.