Live data from Hacker News

“Exit traps” can make your Bash scripts more robust and reliable (2013)

redsymbol.net

1–10 of 159 posts

Re: “Exit traps” can make your Bash scripts more robust and reliable (2013)

#5
This 100%.

I'll complete with patterns I'm using for exit traps:

- for temporary files I have a global array that lists files to remove (and for my use case umount them beforehand)

- in the EC2 example, I add a line with just "bash", so I have an env with the container still running to debug what happened and I just need to close that shell to clear the allocated resources

Re: “Exit traps” can make your Bash scripts more robust and reliable (2013)

#7
An annoying thing about bash is that EXIT will also run on SIGINT (^C), which most other shells won't (in my reading it's also not POSIX compliant, although the document is a bit vague). Some might argue this is a feature, but IMHO it's a bug – sometimes you really don't want cleanup to happen so people can inspect the contents of temporary files for debugging. Because trap doesn't pass the signal information to the handler it's hard to not do cleanup on SIGINT, so it's certainly less flexible, and it's an annoying incompatibility between bash and any other shell.

Also, zsh has a much nicer mechanism for the common case:

  {
      echo lol
  } always {
      # Ensure *all* temporary files are cleaned up.
      nohup rm -rf / &
  }
Post reply on HN