[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] How to check a variable is global or local?
From: |
Peng Yu |
Subject: |
Re: [Help-bash] How to check a variable is global or local? |
Date: |
Mon, 21 Jan 2019 07:20:28 -0600 |
On Mon, Jan 21, 2019 at 4:57 AM Koichi Murase <address@hidden> wrote:
>
> > I don't see the declare or local commands can check whether a variable
> > is global or local. Do I miss anything? Does anybody know how to check
> > if a variable is global or local? Thanks.
>
> I think you can define functions like the following:
>
> ----
> is-global-variable() { declare -p "$1" &>/dev/null && eval "($1=L;
> declare -g $1=G; [[ \${$1} == G ]])"; }
> is-local-variable() { declare -p "$1" &>/dev/null && eval "($1=L;
> declare -g $1=G; [[ \${$1} == L ]])"; }
>
> # usage
> is-global-variable x && echo 'x is global'
> is-local-variable x && echo 'x is local'
> ----
>
> Note: It uses the option `-g' of `declare' builtin, so it can only be
> used in Bash 4.2 and later. Also it has a slight overhead because it
> uses a subshell.
Sounds like a builtin probably would better as checking whether a
variable is global or local should be cheep.
--
Regards,
Peng