help-bash
[Top][All Lists]
Advanced

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

[Help-bash] How to check a variable is global or local?


From: Peng Yu
Subject: [Help-bash] How to check a variable is global or local?
Date: Sun, 20 Jan 2019 12:07:09 -0600

Hi,

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.

$ cat main.sh
#!/usr/bin/env bash
# vim: set noexpandtab tabstop=2:

set -v
function f {
  declare x
  declare -p x
}

f
declare x
declare -p x
$ ./main.sh
function f {
  declare x
  declare -p x
}

f
declare -- x
declare x
declare -p x
declare -- x
$ help declare
declare: declare [-aAfFgilnrtux] [-p] [name[=value] ...]
    Set variable values and attributes.

    Declare variables and give them attributes.  If no NAMEs are given,
    display the attributes and values of all variables.

    Options:
      -f    restrict action or display to function names and definitions
      -F    restrict display to function names only (plus line number and
            source file when debugging)
      -g    create global variables when used in a shell function; otherwise
            ignored
      -p    display the attributes and value of each NAME

    Options which set attributes:
      -a    to make NAMEs indexed arrays (if supported)
      -A    to make NAMEs associative arrays (if supported)
      -i    to make NAMEs have the `integer' attribute
      -l    to convert the value of each NAME to lower case on assignment
      -n    make NAME a reference to the variable named by its value
      -r    to make NAMEs readonly
      -t    to make NAMEs have the `trace' attribute
      -u    to convert the value of each NAME to upper case on assignment
      -x    to make NAMEs export

    Using `+' instead of `-' turns off the given attribute.

    Variables with the integer attribute have arithmetic evaluation (see
    the `let' command) performed when the variable is assigned a value.

    When used in a function, `declare' makes NAMEs local, as with the `local'
    command.  The `-g' option suppresses this behavior.

    Exit Status:
    Returns success unless an invalid option is supplied or a variable
    assignment error occurs.
$ help local
local: local [option] name[=value] ...
    Define local variables.

    Create a local variable called NAME, and give it VALUE.  OPTION can
    be any option accepted by `declare'.

    Local variables can only be used within a function; they are visible
    only to the function where they are defined and its children.

    Exit Status:
    Returns success unless an invalid option is supplied, a variable
    assignment error occurs, or the shell is not executing a function.


-- 
Regards,
Peng



reply via email to

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