Using traps inside a function in Linux bash script

May 3, 2021

Comments

Adsense

Adsense

Adsense

Adsense

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:

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
Satish Kumar

Satish Kumar

I am Satish Kumar, Founder of LinuxConcept. Linux and F.O.S.S enthusiast, love to work on open source platform and technologies.

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Adsense

Related Posts

Backup of files in Linux using command line

In IT or our day-to-day computer industry activities, taking backup is one of the most important activities. Previously, offices were required to keep important paper in a safe place; but if a fire breaks out, then everything is finished. In the digital world, taking...

Using awk in Linux

awk is a program that has its own programming language for performing data-processing and generating reports. The GNU version of awk is gawk. awk processes data, which can be received from a standard input, input file, or as the output of any other command or process....

0 Comments

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

eleven + nineteen =

News & Updates

Join Our Newsletter

Adsense

Adsense

Adsense

Adsense