0
function double {
    read -p "Enter the value: " value
    return $(($value * 2))
}

result=$(double)

echo "The new result is $result."

When I run this piece of code the echo command doesn't print the computed value, but when I changed result=$(double) to double; result=$? it worked. Why can't I just assign the return value directly?

buzzzen
  • 81
  • 5
  • 1
    The result of a command substitution like `$(double)` is the standard output of the command, NOT its exit status (which is what `return` sets). Using `echo` instead of `return` would be one solution (and would allow you to produce results outside of the 8-bit range supported by status codes). – jasonharper Jan 09 '23 at 02:03
  • A shell function, despite of its name, does not have a _return value_ (shell functions are more like _subroutines_ in other languages). Therefore there isn't anything you can assign. A function can set an exit code on return, and this is something you can assign (but the cases where you want to do it, are rare). I think you need to describe more in detail, what exactly you want to achieve. – user1934428 Jan 09 '23 at 11:54

0 Answers0