In a Bash script, you can defer running a command by using trap like this:

touch /tmp/mytempfile
trap "rm -f /tmp/mytempfile" EXIT

# ... continue your script without a care in the world

This will make sure your temp file is deleted when the script finishes running, even if there were errors.

You can also run a function (e.g. trap my_cleanup_function EXIT), or change EXIT to a signal like SIGINT.

Final thoughts

AI taught me this one. What a time to be alive.

Previous on Linux
Mastodon Mastodon