[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: functions can fully unset local vars in other scopes
From: |
Kerin Millar |
Subject: |
Re: functions can fully unset local vars in other scopes |
Date: |
Fri, 29 Jul 2022 09:51:37 +0100 |
Hi Emanuele,
On Fri, 29 Jul 2022 03:59:07 +0200
Emanuele Torre <torreemanuele6@gmail.com> wrote:
> Description:
> `bash' does not let `unset' fully undeclare local variables. (so that
> they can be used later as `local' variables without needing to
> redeclare them I assume.)
>
> bash-5.1$ x=abc; declare -p x; unset -v x; declare -p x
> declare -- x="abc"
> bash: declare: x: not found
>
> bash-5.1$ a () { local x=abc; local -p x; unset -v x; local -p x ;}
> bash-5.1$ a
> declare -- x="abc"
> declare -- x
>
> However, other functions are allowed to delete those variables:
>
> bash-5.1$ a () { local x=abc; b; local -p x ;}
> bash-5.1$ b () { unset -v x ;}
> bash-5.1$ a
> bash: local: x: not found
>
> This enables defininng a "really_unset" function like so:
>
> really_unset () { unset "$@" ;}
>
> Which may be useful I guess.
>
> But I think allowing functions to unset local variables from other
> functions defeats the whole purpose of having that `unset'
> behaviour. This enables `local' variable to unexpectedly become global
> after a function is called.
Though it only goes halfway towards addressing your concerns, 5.0 added a
localvar_unset option that impedes the behaviour of 'popping' from the
outermost scope.
$ bash -c 'x=foo; f1() { local x=bar; f2; x=baz; }; f2() { unset x; declare -p
x; }; f1; declare -p x'
declare -- x="foo"
declare -- x="baz"
$ bash -O localvar_unset -c 'x=foo; f1() { local x=bar; f2; x=baz; }; f2() {
unset x; declare -p x; }; f1; declare -p x'
declare -- x
declare -- x="foo"
>
> Fix:
> I think calling `unset -v x' (where `x' is a local variable not in the
> current scope) should behave as if it was called in the scope of `x',
> so `x' should remain declared in that scope with no attributes and no
> value.
>
> It may be nice to also add a "force" option for `unset' that makes it
> actually unset the variable if it is `local'. Since this could be
> useful in some cases and it won't be possible after the behaviour is
> changed.
>
--
Kerin Millar