Hacker News new | past | comments | ask | show | jobs | submit login

> traps to handle events like being terminated mid-way thru and cleaning up to a sanitized state

Traps are underused. They solve a lot of error-handling and cleanup problems really easily!

Here[1] is a simple example of using a trap to cleanup a tempfile, that safely handles pipeline errors and unexpected exit/return. The same basic idea works for many kinds of error handling, cleanup, or similar work.

If you ever need to cleanup something at the end of a function

    foo() {
        setup_command
        # ...
        cleanup_command
    }
it using a trap might be as simple as moving the cleanup command to trap at the earliest possible time in the function the command can run:

    foo() {
        setup_command
        trap "cleanup_command" RETURN
        # ...
    }
[1] https://gist.github.com/pdkl95/61fc242e7961cc2584a787ed1760c...





Intriguing. I always trap before setting up, on the basis that a script could get interrupted before setup is completed. Is there any general agreement on what the correct order should be?

It probably depends on if the cleanup is safe to run without its setup. For "rm -f", that's true so the trap probably should be first in that case. If you have to worry about strict dependency ordering, trapping first may not be possible.

Of course, the better solution to those situations is to make the cleanup command idempotent ...

(that said, any order is much better than the unfortunately-common style of simply ignoring errors and exceptions.)




Registration is open for Startup School 2019. Classes start July 22nd.

Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | Legal | Apply to YC | Contact

Search: