trap Command trap Execute command on receipt of signal trap [command] [n ...] trap instructs the shell sh to execute the given command when the shell receives signal n or any other signal in the optional list. If the command is omitted, trap resets traps for the given sig- nals to the original values. If the command is a null string (i.e., a string that consists only of one null character), the shell ignores the given signals. If n is zero, the shell ex- ecutes the specified command when it exits. When it is invoked with no arguments, trap prints the signal number and command for each signal on which a trap is set. The shell executes trap directly. ***** Example ***** The following example takes two files and outputs only those lines which are the same. # If input only one file-name then simply "cat". if [ $# = 1 ]; then cat $1 exit 0 # If input two file-names - Ok, else "Usage". else if [ $# != 2 ]; then echo "Usage: cmn file1 [file2]" exit 1 fi fi # TMP is original name of temporary file (/tmp/temp_(pid) TMP=/tmp/temp_$$ # Temporary file has to be removed trap 'rm $TMP; exit 1' 1 2 9 # Difference between "file1" and "difference between file1 and file2" # is the common strings "file1" and "file2" # The strings that are in "file1" and absent in "file2" print in TMP. diff $1 $2 | sed -n -e "s/^< //p" > $TMP COHERENT Lexicon Page 1
trap Command trap # The strings that are in "file1" and absent in TMP print in stdout. diff $1 $TMP | sed -n -e "s/^< //p" # Remove temporary file rm $TMP ***** See Also ***** commands, sh, signal COHERENT Lexicon Page 2