help-bash
[Top][All Lists]
Advanced

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

Re: Issues modifying a local variable inside of a subfunction


From: Greg Wooledge
Subject: Re: Issues modifying a local variable inside of a subfunction
Date: Mon, 11 Oct 2021 23:02:45 -0400

On Mon, Oct 11, 2021 at 09:08:46PM -0500, Hunter Wittenborn wrote:
> #!/usr/bin/env bash
> test1() {
>   variable="${1}"
>   declare -g "${variable}=1"
> }
> 
> test2() {
>   local number=0
>   test1 number
>   echo "${number}"
> }
> 
> test2

> Why is this outputting "0" instead of "1"?

test2 declares a local variable named number.  Then it calls test1,
which declares a variable named number at the global scope.

When control returns to test2, test2 is still using its local variable
named number, not the global variable named number.

Are you actually trying to figure out how to return a value from a function
to its caller?  Doing backflips?  Contortions?  Struggling against the
impossible?  Welcome to bash.

https://mywiki.wooledge.org/BashProgramming#Functions

https://mywiki.wooledge.org/BashFAQ/084

(The BashProgramming page is more comprehensive.)



reply via email to

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