Skip to content
This repository has been archived by the owner on May 7, 2024. It is now read-only.

The Scoping Trap

Mingye Wang edited this page Mar 7, 2016 · 8 revisions

In autobuild many loadings are done with functions:

  • abrequire is a function
  • abloadlib is a function
  • Even . is a function (silly, right?)

And when you use declare, many things are held into the local scopes of the functions, e.g.:

.(){ command . "$@"; }
. /dev/fd/42 42<<'EOF'
declare -A foo
foo[bar]=buz
declare -p foo # good
EOF
declare -p foo # missing

The solution? Use declare -g. This messes up with the very-top-level scope, but it's better than losing your thing.

If you really hate mess-ups, go for evals. We are trying hard to figure out a good varname for this very very evil purpose.

.(){ command . "$@"; }
. /dev/fd/42 42<<'EOF'
to_eval='declare -A foo
foo[bar]=buz'
EOF
eval "$to_eval"
declare -p foo
Clone this wiki locally