trap command

Hello experts!

I need to know the use of trap command please

In one of our program we have

trap "rm -f temp1 ; exit 1" 1 2 15 0

and program always exit with 1

there is a rm -f temp1 as well at the end of the program

as

rm -f temp1
exit 0

when I test a probram with set -x
it gives

rm -f temp1
exit 0
rm -f
exit 1

what could be the use of trap in this case please?

Thanks and Regards,
Ram.

The trap is there so that, if it dies unexpectedly from any of the signals 1, 2, 15, or 0(a special signal number that just means exit), the file will still be deleted.

As for why it's not working, without seeing the code I can't even guess.

This would probably better as:

trap "rm -f temp1 ; exit 1" 1 2 3 15

As described above, the trap on signal "0" is being executed on normal exit from the script after the last two lines of the script have been executed.
I'd include signal "3" (intr) in the list to cover those times when you type the interrupt sequence from the keyboard (usually but not always ctrl/c).

In your research on the trap command, note that you can use the kill command to send a signal to a program, as well as enter various Ctrl characters typed at the keyboard which send a signal too (which you can trap as needed).

Ask the google about traps and signals for more info.

Gary

You might want to change the exit 1 in the trap to just exit . This allows the exit code used when the trap was invoked to pass through. Thus if a script aborts with an exit 2 the exit code available to the parent process will be 2. More importantly, if the script exits with a zero ( exit 0 ) that zero (success) is made available to the parent, and the desired cleanup is done.

trap "rm -f tmp-file; exit" EXIT 1 2 3 15

This is certainly available with Kshell; I assume bash has implemented it as well, but I cannot say.