In bash getting weird output from function ?

My script-

result=""
times()
{
echo "inside the times function"
result=8
echo "Inside function $result"
return $result
}
result=$(times)
echo "the value is "$?
echo "the value of result $result"

when I run I get this, why the value still remain 0.

$ ./func
the value is 0
the value of result 0m0.015s 0m0.031s
0m0.000s 0m0.000s

Even the echo command also did not print anything.

Hi.

times is a shell built-in. Choose a different name for your function.

$ cat myTest 
result=""
xtimes()
{
echo "inside the times function"
result=8
echo "Inside function $result"
return $result
}
result=$(xtimes)
echo "the value is "$?
echo "the value of result $result"

$ ./myTest
the value is 8
the value of result inside the times function
Inside function 8

This works for me (with bash 2 and 3).

the value is 8
the value of result inside the times function
Inside function 8

But to be on the safe side, use a different name for your function, because times is the name of a shell builtin function.

oh g8t, I changed the name it worked. But also 1 more thing to notice here is, it did not echo the value of global variable.

the value of result

The value of $result is that of the two echo's inside the function (in red) - not to be confused with the return value of the function (8):

the value is 8
the value of result inside the times function
Inside function 8

and is echo'd correctly.

Scott, Thank you. You are the real expert. As I am a java programmer, I thought it will work this way-

result=$(times)

It will call times function and the return value will go in variable result. But no, the control went to result. So this result will be used to call the function.:eek: