I have a somewhat difficult time figuring out how - if possible - to return from a higher function, let me show you a POSIX code tidbit:
sudoedit_err ()
{
printf >&2 'Error in sudoedit_run():\n'
printf >&2 '%b\n' "$@"
}
sudoedit_run ()
{
# `sudoedit` is part of `sudo`'s edit feature
if ! command -v sudo > /dev/null 2>&1; then
sudoedit_err "'sudo' is required by this script."
return 1
fi
# primary non-empty arguments check
if ! { [ $# -ge 3 ] && [ -n "1ドル" ] && [ -n "2ドル" ] && [ -n "3ドル" ]; } then
sudoedit_err "Low number of arguments.\\nExpected: \1ドル = editor type; \2ドル = editor name; \3,ドル (\4ドル), ... = file(s).\\nPassed $#: $*"
return 1
fi
...
Important notes first:
These functions are sourced to my shell directly from the
.bash_aliases
file = which is sourced by my.bashrc
in effect.What I would like: The
sudoedit_err
be able to return directly, which I am not able to do, I am quite sure I just missed a class of POSIX scripting. 😠️In spite, my default shell is Bash, the solution must be POSIX-compliant.
What I found out:
- One can't use
exit 1
instead ofreturn 1
= it would exit the terminal.
1 Answer 1
A couple of people have suggested a subshell, which I think is a good idea. Using that, you can introduce a wrapper function that invokes a second function in a subshell. With that, any function that that second function calls can invoke exit
to terminate the subshell.
Here's an example based on your original post:
sudoedit_err() {
printf >&2 'Error in sudoedit_run():\n'
printf >&2 '%b\n' "$@"
exit 1
}
_sudoedit_run() {
# `sudoedit` is part of `sudo`'s edit feature
if ! command -v sudo > /dev/null 2>&1; then
sudoedit_err "'sudo' is required by this script."
fi
# primary non-empty arguments check
if ! { [ $# -ge 3 ] && [ -n "1ドル" ] && [ -n "2ドル" ] && [ -n "3ドル" ]; } then
sudoedit_err "Low number of arguments.\\nExpected: \1ドル = editor type; \2ドル = editor name; \3,ドル (\4ドル), ... = file(s).\\nPassed $#: $*"
fi
}
sudoedit_run()
{
(_sudoedit_run "$@")
}
You wouldn't want to call the wrapped function directly since that'd terminate your shell.
You must log in to answer this question.
Explore related questions
See similar questions with these tags.
exit 1
.