bug-bash
[Top][All Lists]
Advanced

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

Re: Passing variables by reference conflicts with local


From: Clark Wang
Subject: Re: Passing variables by reference conflicts with local
Date: Fri, 27 Apr 2012 10:29:42 +0800

On Fri, Apr 27, 2012 at 02:49, Greg Wooledge <wooledg@eeg.ccf.org> wrote:

>
> I don't see this as a surprise.  It's how you return values from functions
> in bash.  Pick a global variable (r, ret, whatever you want) and stuff the
> return value into that.  You can even declare your "r" locally somewhere
> so that the value never propagates up higher than that point in the call
> chain.
>

I can understand this but I've never written code like this. Will try it
later.

>
> For example:
>
> # Return random number from 0 to ($1-1) in variable "r"
> rand() {
>  local max=$((32768 / $1 * $1));
>  while (( (r=$RANDOM) >= max )); do :; done
>  r=$((r % $1))
> }
>
> foo() {
>  local r
>  rand 42
>  ... use $r ...
> }
>
> foo
> ... we don't see "r" here because it was scoped only within foo & its kids
> ...
>
>


reply via email to

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