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: Frans de Boer
Subject: Re: [Help-bash] Updating global variable from recursing function.
Date: Mon, 02 Apr 2012 22:33:15 +0200
User-agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.28) Gecko/20120306 SUSE/3.1.20 Thunderbird/3.1.20

On 04/02/2012 09:17 PM, Greg Wooledge wrote:
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

I stand corrected:
#!/bin/sh
#
declare -i iTest1=0
declare -i iMax=7

function recursetest () {

 iTest1=$((iTest1+1))
 if (( iTest1 < iMax )); then recursetest; fi
}

function testcaller () {
  recursetest
}

echo "1 - recursetest=$iTest1"
testcaller
echo "2 - recursetest=$iTest1"
------------------
Is producing the right result while using [[ does not.
That leaves a puzzle for me to check why the trace showed correct results before a return.

Anyhow, thanks for pointing me in the right direction.

Regards, Frans.




reply via email to

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