How to clear trap

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← trap statementHomeInclude trap statements in a script →

To clear a trap use the following syntax:

trap - signal
trap - signal1 signal2

For example, set a trap for rm command:

file=/tmp/test4563.txt
trap 'rm $file' 1 2 3 15
trap

To clear SIGINT (2), enter:

trap - SIGINT
trap

To clear all traps, enter:

trap - 1 2 3 15
trap

Create a shell script called oddoreven.sh:

#!/bin/bash
# Shell script to find out odd or even number provided by the user
# ----
# set variables to an integer attribute
declare -i times=0
declare -i n=0
 
# capture CTRL+C, CTRL+Z and quit singles using the trap
trap 'echo " disabled"' SIGINT SIGQUIT SIGTSTP
 
# set an infinite while loop
# user need to enter -9999 to exit the loop
while true
do
        # get date
	read -p "Enter number (-9999 to exit) : " n
        # if it is -9999 die 
	[ $n -eq -9999 ] && { echo "Bye!"; break; }
        # find out if $n is odd or even
	ans=$(( n % 2 ))
        # display result 
	[ $ans -eq 0 ] && echo "$n is an even number." || echo "$n is an odd number."
        # increase counter by 1
	times=$(( ++times ))
done
 
# reset all traps 
trap - SIGINT SIGQUIT SIGTSTP
 
# display counter
echo "You played $times times."
exit 0

Save and close the file. Run it as follows:

chmod +x oddoreven.sh
./oddoreven.sh

Sample outputs:

Enter number (-9999 to exit) : 2
2 is an even number.
Enter number (-9999 to exit) : 999
999 is an odd number.
Enter number (-9999 to exit) : ^C disabled

0 is an even number.
Enter number (-9999 to exit) : -9999
Bye!
You played 3 times.
← trap statementHomeInclude trap statements in a script →