bug-bash
[Top][All Lists]
Advanced

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

Re: bug attached


From: queency3 jones
Subject: Re: bug attached
Date: Thu, 31 Aug 2023 22:38:55 +0300

i don't think that main is significant when it declared in "Bash" but even
though,
if you change the function main , to function ain  the $aa should be local
, but it ain't !!


On Wed, Aug 30, 2023 at 5:59 PM Andreas Kusalananda Kähäri <
andreas.kahari@abc.se> wrote:

> On Wed, Aug 30, 2023 at 03:40:21PM +0300, queency3 jones wrote:
> >
>
> > From: queency3@gmail.com
> > To: bug-bash@gnu.org
> > Subject: 2 same var name in different function causing mix
> >
> > Configuration Information [Automatically generated, do not change]:
> > Machine: x86_64
> > OS: linux-gnu
> > Compiler: gcc
> > Compilation CFLAGS: -g -O2
> -fdebug-prefix-map=/build/bash-2bxm7h/bash-5.0=. -fstack-protector-strong
> -Wformat -Werror=format-security -Wall -Wno-parentheses -Wno-format-security
> > uname output: Linux debian 4.19.0-25-amd64 #1 SMP Debian 4.19.289-2
> (2023-08-08) x86_64 GNU/Linux
> > Machine Type: x86_64-pc-linux-gnu
> >
> > Bash Version: 5.0
> > Patch Level: 3
> > Release Status: release
> >
> > Description:
> >
> > function sub { aa=8;return_value=$aa; }
> > function sub { aa=8; }
> >
> > function main { aa=3;sub;aa=$(($aa+1));printf "$aa\n"; }
> >
> >
> > calling main will print 9 instead of 4
> >
> >
>
> Not a bug.
>
> The code outputs "9" because the scope of the variable "aa" is global
> (once it has been created in "main").  The second function "sub" will
> therefore modify the value of the variable "aa" in the global scope.
> The change in the variabel's value will be visible in "main" after the
> call to "sub".
>
> To make the variable local to the "sub" function, use the "local"
> keyword:
>
>         function sub { local aa=8; }
>
> This will create a local variable "aa" in the function "sub" that will
> not be visible outside of the function.  In particular, it will not
> overwrite the global variable "aa" in "main" and the value of "aa" in
> "main" will remain unchanged (until you increment it from "3" to "4").
>
> On an unrelated note, you sohuld be printing the value using a static
> formatting string, like so:
>
>         printf '%s\n' "$aa"
>
> This avoids interpreting the value of the variable as a printf formatting
> string.
>
> --
> Andreas (Kusalananda) Kähäri
> SciLifeLab, NBIS, ICM
> Uppsala University, Sweden
>
> .
>


reply via email to

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