2

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.

marked as duplicate by muru, vonbrand, roaima, Philippos, DarkHeart Aug 14 at 5:11

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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. – mosvy Aug 11 at 20:58
4

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
  • 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 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 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. – mosvy Aug 11 at 21:03

Not the answer you're looking for? Browse other questions tagged or ask your own question.