#!/bin/bash # # File: trap.sh # # Description: A script to understand the trap command and signal handling. # The script first creates a file in /tmp and sets up the trap command to # rm the file if the user enters a control-c (INT signal) at the terminal. # The second part of the script executed once the user enters a control-c # resets the trap command to NULL (no action) # # Input: control-c (INT) from user. # # Output: Prints out whether the created file exists or not. # # Modified from Linux Programming (Matthews, Stones) # trap 'rm -f /tmp/myfile_$$' INT echo create file /tmp/myfile_$$ date > /tmp/myfile_$$ printf "Press control-c to interrupt ...\n" while [ -f /tmp/myfile_$$ ]; do printf "File /tmp/myfile_$$ exists\n" sleep 1 done ls /tmp/myfile_$$ printf "See the file /tmp/myfile_$$ does not exist\n" # This time around the trap is reset to no action. # The control-c forces the script to end because there is no action. # The default behavior is to immediately terminate the script if there # is no command associated with the trap. trap INT echo create file /tmp/myfile_$$ date > /tmp/myfile_$$ printf "Press control-c to interrupt ...\n" while [ -f /tmp/myfile_$$ ]; do printf "File /tmp/myfile_$$ exists\n" sleep 1 done ls /tmp/myfile_$$ printf "See the file /tmp/myfile_$$ does not exist\n" exit 0