All of the posts here are actually correct, but they may appear little confusing. So I will try to sort them out a little.
The functions in bash are handled different from C/C++. Let's say you define
Code:
function myfun {
echo "calling my function"
return 1
}
Than if you call it this way:
the function is executed and writes "calling my function" to the screen. The return value is stored in variable "$?". Ultimately
will behave exactly as function in C/C++ storing returned value in MYFUN_RET variable.
But be careful.
Code:
MYFUN=$(myfun)
MYFUN_RET=$?
MYFUN_RET will still hold return value of your function, but otherwise it will behave different. It will store output of "myfun" function to variable MYFUN. So there will be no output to screen. But if you later do
you will get "calling my function". In other words construction VARIABLE=function does not store return value into VARIABLE, but output of the function.
Now to that if commands. I think the difference between
and
is explained quite clearly in the above post. But there is one small trap hidden. When using
it does not evaluate the return code of "command" if "command" is your internal function. It will return the value of call to that function.
So if you want a function to do something and than evaluate its return value, the construction should look like
Code:
myfun
if [ $? ]
then
echo one 1
else
echo zero 0
fi