pepero
pepero

Reputation: 7513

assign output of function to variable in bash shell

function to_call()
{
    echo "#1 is $1"
}

function call() 
{
    local val=$(to_call testInput)
}

There is no output on terminal. why?

if I change it to:

function to_call()
{
    echo "#1 is $1"
    return 1
}

function call() 
{
    local val=$(to_call testInput)
    echo "value is $val"
}

Instead of "value is 1", it is "value is #1 is testInput". What happens?

Is there any way that i could print the echo of the "to_call function" on terminal, and also use the return state?

Upvotes: 2

Views: 2466

Answers (1)

pce
pce

Reputation: 5921

Theres no output, because of command substitution (which invokes a subshell) and reassigns the output, ie. the function's output to stdout is reassigned to the local variable.

The bash return statement is to specify a status only, like exit without terminating the shell. It allows to return a "exit status" ($?) of the function.

Variables in the scope of a subshell are not accessible to the parent process.

Upvotes: 2

Related Questions