pepero pepero - 4 months ago 9
Bash Question

assign output of fucntion 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?

pce pce
Answer

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.

To assign output to stdout and capture the output of the subshell, you could use a global Variable.

Comments