Browsing around...
News  News Links  Links Blog  Blog Italiano  Español 
11 - System signals in the bash


A signal is a kind of "message" that a program can send to another program; an example can be the hit of the CRTL + C keys combination, which produces an INT signal, which usually stops the script execution.
"Masking" a signal in a script means associating to this signal a function to be executed when the signal is received. In the bash the system signals can be masked through the trap signal, according to the following syntax:

trap function_name signal_name

Here there's an example:


# The following script shows the usage of the trap function.
# In the function three countdowns from 10 seconds are present.
# You can try to stop the countdowns by pressing CRTL-C
# (INT signal) and verifying the script behaviour.
# During the first countdown, the INT signal is masked by an
# error function: the arrival of this signal causes the script
# to display this error message.
# Then during the second countdown the signal INT is disabled:
# its reception causes no effect.
# Finally durign the third countdown the mask is removed:
# it is now possible to stop the count.

function error
  echo "Sorry, no interruption allowed"
  sleep 3

function start_count
  for i in 10 9 8 7 6 5 4 3 2 1;
    echo "$i seconds have passed"
    sleep 1

# Main program

####### Count 1

trap error INT # Masking of the signal with an errror function
echo "Count 1:"
echo " "

####### Count 2

trap '' INT # Signal disabling
echo "Count 2:"
echo " "

####### Count 3

trap - INT # Mask deletion
echo "Count 3:"




No comment present!

Write a comment

You can write here a comment to the article you've just read. Smiles, links and images are not allowed. The maximum comment length is 4000 characters. Please be polite, all the offensive messages will be deleted.

Your comment (lascia bianco!):
Uses (max 25 characters, required)
Web site (max 255 characters, optional)
e-Mail (max 255 characters, optional, will not be published) Your opinion (lascia bianco!):
Comment (max 4000 characters, required):

Valid HTML 4.01 Transitional
E-Mail - 88.16 ms

Valid HTML 4.01 Transitional