2

Suppose I have a function "func" which gets two arguments "a" and "b" and returns something. For some reason I can't manage echo what I get from the function.

This is what I tried:

value=$(func $a $b)
echo $value

1 Answer 1

3

Since you didn't show your function definition, this is only a guess, but I'm pretty confident it's a good one.

You need to understand that a function in shell fits into the language as if it was a command, i.e. a separate program, and the return keyword is analogous to exit. You can only return small integers, and the caller sees them in $?, just like the exit value of any other command.

Functions can also output a result to stdout by using echo (or any other command that prints to stdout), and then the result can be caputred with $(func args ...)

So you probably just need to change return to echo in your function.

Sign up to request clarification or add additional context in comments.

2 Comments

My function returns using "return" statement, since I want to finish the function once it returns some value.
So change it to an echo followed by a return 0 if you want the function to be considered successful, or return 1 if you want it to fail. Just like writing an independent program - you do your output then exit. Except the "exit" from a shell function is spelled "return".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.