Magazine

Using Traps Inside a Function in Linux Bash Script

Posted on the 03 May 2021 by Satish Kumar @satish_kumar86

If we use thetrapcommandinsidea function in the script, then the reassigned signal behavior will become global inside a script. We can check this effect in the followingscriptexample.

Let’s write shell scripttrap_01.shas follows:

trap_01.sh

#!/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:

Output:

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

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

trap_02.sh

#!/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 'bye' to exit)." 
while true 
do 
    echo "Rolling...c" 
    read string 
    if [ "$string" = "bye" ] 
    then 
        break 
    fi 
done 
echo "Exiting normally" 

Let’s test the program as follows:

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

Output:

Output:

Enter any string (type 'bye' to exit).Rolling...c^Ccaught signal SIGINTbyeExiting normally

Back to Featured Articles on Logo Paperblog