help-bash
[Top][All Lists]
Advanced

[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: Koichi Murase
Subject: Re: [Help-bash] How to check a variable is global or local?
Date: Mon, 21 Jan 2019 19:57:13 +0900

> 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.

Regards,
Koichi



reply via email to

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