Note: this is not a duplicate of In bash, is there an equivalent of die "error msg" , as illustrated at the end of this post.
Consider the shell function
foo () {
echo "testing..." 1>&2
return 1
echo "should never reach this point" 1>&2
}
The following shows foo
's expected behavior:
% foo || echo $?
testing...
1
I would like to encapsulate the functionality shown in the first two lines of foo
in a function die
, so that the definition of foo
could be reduced to
foo () {
die 1 "testing..."
echo "should never reach this point" 1>&2
}
...while still preserving its original behavior.
My interest is primarily zsh
, but would also be interested in answers suitable for bash
and/or /bin/sh
scripts, if they're different.
BTW, this won't work:
die () {
local exit_code=$1
shift
echo "$*" 1>&2
exit $exit_code
}
If one ran from the command line a version of foo
that used this die
, the result would be to kill one's current shell (at least this is the result I get when I try something similar). This is why this question is not a duplicate of In bash, is there an equivalent of die "error msg". At any rate, the answer to that other question won't satisfy my requirements here.