2

A typical way for a shell function to "return" its result is to assign it to some global variable.

Is there any convention/best-practice on the name of this variable?

  • Is that typical? Returning values in always the same variable would be awkward with concurrent calls. I would have thought that just outputting the value and using command substitution would be more typical, even though it does start a subshell every time. But I don't know. – ilkkachu May 16 '17 at 15:14
  • 1
    @ikkachu, see how $?, $! is always the same variable. It's a common way to do things in shells. Command substitutions cannot always be used (for instance, because it starts a subshell which makes you lose all the changes done by that command (like a function)). – Stéphane Chazelas May 16 '17 at 15:28
5

REPLY is commonly used for that. It's used by read and select in bash, ksh and zsh at least.

In the zsh documentation:

REPLY
This parameter is reserved by convention to pass string values between shell scripts and shell builtins in situations where a function call or redirection are impossible or undesirable. The read builtin and the select complex command may set REPLY, and filename generation both sets and examines its value when evaluating certain expressions. Some modules also employ REPLY for similar purposes.

reply
As REPLY, but for array values rather than strings.

Beware of potential implications when changing the type of that variable though.

Another approach would be to pass the name of the variable as argument:

get_date() {
  local date
  date=$(date)
  eval "$1=\$date"
}

That doesn't work if calling get_date with a variable called date. ksh93 addresses that by introducing namerefs which are a way to reference variables in the scope of the caller. bash recently added nameref support, but they reference variables in the same scope (by name only), so are not useful for that.

function get_date {
  typeset -n var=$1
  var=$(date)
}

In ksh93, that works even if called as get_date var. There are ways to make it work in bash, mksh and yash by exploiting a bug of unset, but I wouldn't go there as the bug may be fixed in the future.

Another way would be to not use local variables in your functions that set arbitrary variables other than the $1, $2... position parameters. That can make for pretty unreadable code though. See for instance that implementation of a getopts_long shell function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.