variables-and-scoping.org 5.1 KB

Some examples of scoping in bash. Because I forget. This makes it clear.

Print shell verion

date
echo SHELL is $SHELL
echo BASH_VERSION is $BASH_VERSION
Thu Nov 17 03:49:42 AM EST 2022
SHELL is /bin/bash
BASH_VERSION is 5.1.16(1)-release

Test/demonstrate scoping of variables in bash functions

Code

date
echo

FOO=FOO-set-outside-functon
function baz { echo inside baz FOO is $FOO; FOO=FOO-set-inside-inside; }
baz
echo FOO is $FOO

Conclusions

Bash variables are simply global.

Thu Nov 17 03:44:59 AM EST 2022
inside baz FOO is FOO-set-outside-functon
FOO is FOO-set-inside-inside

Test/demonstrate scoping of variables in bash functions using subprocesses

Code

date
echo

FOO=FOO-set-outside-functon
function baz { (echo inside baz FOO is $FOO; FOO=FOO-set-inside-inside;) }
echo
baz
echo
echo FOO is $FOO
Thu Nov 17 03:52:35 AM EST 2022


inside baz FOO is FOO-set-outside-functon

FOO is FOO-set-outside-functon

Conclusions

Running in a sub-shell, the function receives copies (via fork(2)) of global variables, but then they, and any variables defined in the function remain local to the function. This is better. Only downside is creation of a process … heavy-weight operation. OK if not used in heavy processing

Thu Nov 17 03:44:59 AM EST 2022
inside baz FOO is FOO-set-outside-functon
FOO is FOO-set-inside-inside

Test/demonstrate scoping of EXPORT variables in bash

Code

date


# set FOO to known state
unset FOO
FOO=bar

# expand FOO in "normal" function
function f { echo In f, FOO is $FOO; }
f

# expand FOO in "subprocess" function
function g { (echo In g, FOO in subprocess is $FOO) }
g

# expand FOO in a separate command/script
cat > h <<'EOF'
#! /bin/bash
set -u
[[ -v FOO ]] && echo in h FOO is $FOO || echo in h FOO is not defined
EOF
chmod +x h
./h
# not defined

# export it, now seen via ENV
export FOO
./h
Thu Nov 17 04:14:03 AM EST 2022
In f, FOO is bar
In g, FOO in subprocess is bar
in h FOO is not defined
in h FOO is bar

Conclusions

EXPORTED variables are visible to other commands.

Raw stuff - move up