|
From: | Frans de Boer |
Subject: | Re: [Help-bash] Updating global variable from recursing function. |
Date: | Mon, 02 Apr 2012 23:44:47 +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 10:33 PM, Frans de Boer wrote:
As a final, I changed all [[ into (( when it was a pure integer comparison in my script and all is working well. I think it is also the source of some other problems I encountered with recursion of deeper nesting of functions.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 7Every 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 0I 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.
Seems, I did not understood the difference between [[ and (( in string and integer comparisons. Back to school to study more :\
Again thanks, Frans.
[Prev in Thread] | Current Thread | [Next in Thread] |