help-bash
[Top][All Lists]
Advanced

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

Re: [Help-bash] Updating global variable from recursing function.


From: Greg Wooledge
Subject: Re: [Help-bash] Updating global variable from recursing function.
Date: Mon, 2 Apr 2012 15:17:32 -0400
User-agent: Mutt/1.4.2.3i

On Mon, Apr 02, 2012 at 09:08:12PM +0200, Frans de Boer wrote:
> Strange, it is working fine, the counter is incremented but the result 
> is never propagated to the real global variable, as shown by the bash -x 
> output.

imadev:~$ cat foo
#!/bin/bash

foo() {
  local i=7
  if ((i > max)); then max=$i; fi
}

max=0
foo
echo "max is $max"

imadev:~$ ./foo
max is 7


> Every time the function returns to the caller, the iHiMDirNest is 
> restored to the level it was before being calling.

That suggests that the variable is in fact local, in some scope or
other.  Are you sure you showed us the *uppermost* scope?  For example,
this would do it:

imadev:~$ cat bar
#!/bin/bash

bar() {
  local max
  foo "$@"
}

foo() {
  local i=7
  if ((i > max)); then max=$i; fi
  echo "inside foo, max=$max"
}

max=0
bar
echo "at global scope, max is $max"

imadev:~$ ./bar
inside foo, max=7
at global scope, max is 0



reply via email to

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