1

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 of return 1 = it would exit the terminal.
2
  • I think your best bet there is to (1) make this a script instead of a set of functions in your environment, then (2) use exit 1. Nov 7, 2020 at 14:22
  • I should have prefixed my previous comment with "I don't think what you want is doable." Nov 7, 2020 at 14:30

1 Answer 1

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.

0

You must log in to answer this question.

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