1

In Bash I want to be able to write something like:

tst() {
  [ -z "$1" ] && die "No parameters provided!"
  # do whatever
}

but I cannot define die like this:

die() {
  echo "$*"
  exit 1
}

because if my test function is running in my current shell (e.g. . ./file-with-function) then it aborts my current session. what I really want it to do is something more along the lines of:

tst() {
  [ -z "$1" ] && echo "No parameters provided!" && return
}

but I want to do the echo and return in a single function call. is there a clever way to do this?

2 Answers 2

2

See How to detect if a script is being sourced for explanation of the [[ ${BASH_SOURCE[0]} == $0 ]] trick.

die () {
    msg=$1
    code=${2:-1}
    echo "$msg" >&2
    if [[ ${BASH_SOURCE[0]} == $0 ]] ; then
        echo exit $code
    else
        echo return $code
    fi
}

This function returns what should be called to die in the current context, so you have to call it in a special way:

(( $# )) || $(die 'No parameters!')
2
  • ah. the trick calling context is the solution. brilliant! Commented May 8 at 0:08
  • 1
    I would upvote but I don't have enough reputation to do it :( Commented May 8 at 0:09
0

another thought: don't use die if you want to keep living:

warn() { echo "$*" >&2; }
die() { warn "$@"; exit 1; }

if something really terrible; then die "I can't continue"; fi
if something bad but tolerable; then warn "That shouldn't happen"; fi
1
  • but you don't show how to abort the function
    – ekkis
    Commented May 10 at 21:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .