Bash – How to assign the output of a command to a variable without running the command in a subshell

bashshell-scriptvariable

If I have a function like this:

TEST()
{
    if [[ "$1" == "hi" ]]
    then
        exit 1
    fi

    echo "Some text"
}

and if I run the function in the current shell with:

TEST "hi"

everything works as expected. The if statement in the function will be true, and the entire script will exit.
If I do this on the other hand:

FUNCTION_OUTPUT=$(TEST "hi")

So that I can catch the stdout from the function in a variable, the if statement inside the function will still be true, the "exit 1" will still fire, but since we are running in a subshell, the script will keep going.

Instead of using VAR_NAME=$() to run something in a subshell and assign it to a variable, is there a way to run it in the current shell so that the "exit 1" line in my function actually exits the entire script?

Best Answer

Variable assignment is just a Simple Command, so you can use the if condition to check whether function success of fail:

if ! FUNCTION_OUTPUT=$(TEST hi); then
  echo Function return non-zero status
  exit 1
fi

# This line never printed
printf '%s\n' "$FUNCTION_OUTPUT"

If the function success, you will have the variable FUNCTION_OUTPUT with the result of function:

if ! FUNCTION_OUTPUT=$(TEST hii); then
  echo Function return non-zero status
  exit 1
fi

# Output content of FUNCTION_OUTPUT
printf '%s\n' "$FUNCTION_OUTPUT"
Related Question