[Toybox] how can we return function result in script

Rob Landley rob at landley.net
Fri Jun 30 17:54:06 PDT 2023



On 6/30/23 08:18, Mingliang HU 胡明亮 via Toybox wrote:
> How can we return function value in script? The "return" doesn't work.
> For example:
> 
> #!/bin/sh
> 
> my_function() {
>     echo "Inside my_function"
>     return 2
> }
> 
> my_function
> result=$?
> echo "Function returned: $result"
> 
> 
> The result is:
> .: return: No such file or directory
> .:  : No such file or directory
> .: return: No such file or directory
> .: return: No such file or directory
> .: return: No such file or directory
> .: syntax error '/etc/profile.d/vte-2.91.sh'@40: __vte_osc7

Ah, sorry, I hadn't implemented return yet. Some of the function plumbing is
still in a branch because the lifetime rules seemed a bit non-obvious, but I
think I've got it now:

  $ x() { eval "return 3"; echo hi;}; x; echo $?
  3
  $ x() { source <(echo "echo blah;return 3"); echo $?; echo hi;}; x; echo $?
  blah
  3
  hi
  0
  $ return 37
  bash: return: can only `return' from a function or sourced script

So I have to distinguish _three_ contexts, not just two...

Rob


More information about the Toybox mailing list