# Run a function on interrupt or error

It is sometimes necessary for a script to clean up when exiting prematurely. Perhaps some temporary files are written to, and the execution is halted due to an error or a user interrupt (`ctrl-c`).

We can do so using `trap`:

```bash
cleanup() {
  rm some-temp-file-maybe
  # ... other actions
  exit 1
}

trap cleanup ERR SIGINT
```

We're tying the `cleanup` function to the signals `ERR` and `SIGINT`. This function will be called if the script exits with a non-zero return code or if it is interrupted using `ctrl-c`.

Source: `man trap`


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://notes.eliasnorrby.com/bash/trap-ctrl-c-err-cleanup.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
