3

I have these three lines:

  export bunion_uds_file="$bunion_socks/$(uuidgen).sock";
  "$cmd" "$@" | bunion
  rm -f "$bunion_uds_file"

I need to make sure the last line always executes..I could do this:

  export bunion_uds_file="$bunion_socks/$(uuidgen).sock";
  (
    set +e
    "$cmd" "$@" | bunion
    rm -f "$bunion_uds_file"
  )

or maybe like this:

  export bunion_uds_file="$bunion_socks/$(uuidgen).sock";
  "$cmd" "$@" | bunion && rm -f "$bunion_uds_file" || rm -f "$bunion_uds_file"

I assume creating the subshell and using set +e is slightly less performant etc.

Kusalananda
  • 320,670
  • 36
  • 633
  • 936
Alexander Mills
  • 9,330
  • 19
  • 95
  • 180
  • The common practice is to remove a unix domain socket _before_ binding to it. No try/finally, traps, etc could guard against your script just crashing or being killed by `SIGKILL`. Then the next instance will fail with `EADDRINUSE` when trying to bind to it. –  Aug 11 '19 at 20:58
  • @skozin's [answer](https://unix.stackexchange.com/a/254676/133282) looks promising. – EndlosSchleife Apr 13 '23 at 12:16

1 Answers1

5

You could set a trap:

#!/bin/bash

export bunion_uds_file="$bunion_socks/$(uuidgen).sock"
trap 'rm -f "$bunion_uds_file"' EXIT

"$cmd" "$@" | bunion

This would make the rm -f command run whenever the shell session terminates, except for when terminating by the KILL signal.

As mosvy points out in comments, if this is a socket that needs to be cleaned up before use, it would be easier to remove it before recreating and using it:

#!/bin/bash

export bunion_uds_file="$bunion_socks/$(uuidgen).sock"
rm -f "$bunion_uds_file" || exit 1

"$cmd" "$@" | bunion
Kusalananda
  • 320,670
  • 36
  • 633
  • 936
  • 1
    I like to put the trap code in a function: `cleanup() { rm -f $thefile; }` and then `trap cleanup EXIT` -- I think it's cleaner, and it solves any quoting problems. – glenn jackman Aug 11 '19 at 20:44
  • 1
    @glennjackman You've just introduced a quoting problem in that comment's code, but I get what you're saying. For just deleting a single file in a three line script, I personally think not using a function is ok. – Kusalananda Aug 11 '19 at 20:57
  • Yes, bash (but not dash or zsh) will also call the `EXIT` trap when being killed by a `SIGINT` or `SIGTERM`, but I don't know how wise it is to rely on that. –  Aug 11 '19 at 21:03