[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] Adding missing bash features for safely re-usable bash c

From: Greg Wooledge
Subject: Re: [Help-bash] Adding missing bash features for safely re-usable bash code
Date: Mon, 8 Apr 2013 14:10:11 -0400
User-agent: Mutt/

On Mon, Apr 08, 2013 at 05:51:01PM +0000, adrelanos wrote:
> What about
> functions which are supposed to return different strings depending on
> if/else?

If you are using the stdout capturing paradigm, nothing prevents you
from doing so inside an if statement:

foo() {
  if something; then
    echo "true"
    return 0
    echo "false"
    return 0
  echo "internal error; how did I get here?" >&2
  return 1

However, my personal preference for functions returning values (and this
is not limited to strings; the same applies to integers larger than 255 or
smaller than 0, or floating point values, or arrays) is to hard-code
the variable "r" in both the caller and the callee:

rand() {
  local max=$((32768 / $1 * $1))
  while (( (r=$RANDOM) >= max )); do :; done
  r=$(( r % $1 ))

caller() {
  local r
  rand 17
  if ((r < 10)); then ....

This gives the callee a place to store its return value, without requiring
a subshell, and without requiring the re-parsing of an ASCII stream.
If "r" is declared local in the caller, then its scope is limited to the
caller and the callee.  Otherwise, it's global.  I get to choose.

Of course this means I can't use the variable "r" for any other purpose.
Not that I was going to.  If you don't like that, you can use "___r" or

reply via email to

[Prev in Thread] Current Thread [Next in Thread]