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.

2
  • 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. Commented Aug 11, 2019 at 20:58
  • @skozin's answer looks promising. Commented Apr 13, 2023 at 12:16

1 Answer 1

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
3
  • 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. Commented Aug 11, 2019 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. Commented Aug 11, 2019 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. Commented Aug 11, 2019 at 21:03

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.