0
example (){
......
local var
......
return $var 
}

user_val=$(example $number1 $number2) 

I need user_val and i will it. I got error. Code can't detect the function when I try it this way.

5
  • user_val= example $number1 $number2 I tried it but can not assign Commented Mar 3, 2022 at 16:43
  • 5
    $() captures the output of the command, not the return value. Change return to echo. Commented Mar 3, 2022 at 16:47
  • Replace last line with example "$number1" "$number2"; user_val="$?"; echo "$user_val" Commented Mar 3, 2022 at 16:48
  • @Cyrus Note that that will only work for a numeric value between 0 and 255. Commented Mar 3, 2022 at 16:49
  • Even then, the purpose of a function's return value is not to provide data to the caller, but to provide an exit status indicating whether the function succeeded or failed. "Function" is an extreme misnomer for this particular shell construct. Commented Mar 3, 2022 at 17:21

1 Answer 1

2

@Barmar is correct. Replace return with echo in your function. Using var=$(...) assigns the output of the function to the variable.

When using return the value is saved in $?.

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

2 Comments

Note that the return-code special variable $? is a an 8-bit integer (byte).
an unsigned 8-bit int (char)

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.