Using traps in function

If we use the trap command inside a function in 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 Shell script trap_02.sh as follows:

#!/bin/bash

trap "echo  caught signal SIGINT" SIGINT
trap "echo  caught signal SIGQUIT" 3
trap "echo  caught signal SIGTERM" 15
trap "echo caught signal SIGTSTP" TSTP

echo "Enter any string (type 'dough' to exit)."
while true
do
    echo "Rolling...c"
    read string
    if [ "$string" = "dough" ]
    then
        break
    fi
done
echo "Exiting normally"

Let's test the program as follows:

$ chmod +x trap_02.sh
$ ./ trap_02.sh

Output:

Enter any string (type 'dough' to exit).
Rolling...c
^Ccaught signal SIGINT
dough
Exiting normally
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset