Exit Handling

It is often useful to execute commands when a script is about to exit. For example, you might want to make sure all temporary files are deleted before exiting. A list of commands can be declared in such a way that it is automatically executed when the script exits. Such a list is called an exit handler.

To declare an exit handler, invoke the exit command with the -onexit flag followed by the commands to execute. The commands are saved and will be invoked later when the script is about to exit.

exit -onexit {
    exec rm $tmpfile
    puts "bye bye!"
}

The exit handler runs whether a script exits by an explicit exit command or by running out of commands in a script. Signals which normally call exit, in turn run the exit handler. Thus, if you press ^C and have not changed the default action for SIGINT, the exit handler will be called. Signals that cause an ungraceful exit (i.e., core dump) do not execute the signal handler.

There are a few things which do not make sense inside an exit handler. Redefining the exit handler inside the exit handler does not cause the new exit handler to execute. No attempt is made to execute the exit handler twice. If an error (without a catch) occurs in the exit handler, there can be no recovery.

The exit handler can be removed and queried in the same way as signals. An empty command removes the exit handler. If the -onexit flag is given with no handler at all, the current handler is returned.

expect1.1> exit -onexit foo    ;# set
expect1.2> exit -onexit ...

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.