[Top][All Lists]

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

Have var+func sourced in a subroutine but they don't seem to end up in s

From: L A Walsh
Subject: Have var+func sourced in a subroutine but they don't seem to end up in same scope
Date: Sun, 28 Jul 2019 23:25:24 -0700
User-agent: Thunderbird

I have a shell script that includes a util script via a library-include

The library-include function allows me to source a library file
that is in a relative path off of PATH (a feature not in bash,

What I just noticed was a problem where the included file has
local data needed by the included functions.

I wanted the function and its data to be defined in the original
script, but what it looks like happens, is that the data are
defined as being local to the include, but the function does not.

I tried putting exporting the data and the function with export
but it ended up the same.  The variables weren't defined in the
same scope as the function.

Only when I put the function and the data in a wrapper and call
the wrapper instead do I get them in the same scope.  I.e. --
like this:

util_fn () {

  declare [-x] foo=1
  declare [-x] bar=${foo}2

  real_util_fn() {
    makes use of bar to get 'foo2'

  real_util_fn "$@"

Now 'real_util_fn' behaves like the data, i.e. if I export them

(export bar & export -f util_fn real_util_fn)

only 'util_fn' is accessible in the file doing the include --
i.e. 'real_util_fn' appears to be local to util_fn.

Without the extra function for encapsulating the data+func
it appears that real_util_fn ends up in the scope of
"include's" parent while the variables end up in 'include's
scope because of the declare (the -x seems to be relatively ignored).

I tried throwing a declare in front of the sub, but bash didn't like
that or allow pre-declaring it so as to give it local context.

Why does bash disallow this?:

declare -f util_fn
util_fn() { :;}


declare util_fn() { :; }

which, it seems would declare util_fn local to a subs
in the same way:
declare foo=val

does?  Seems rather awkward to need to enclose a sub/within a sub to
achieve same scope.

Note, -g does work to put the vars in the same scope in this case because
the including file is at top scope, but if the included file wasn't at
top scope
I don't think it would.  Even if it did, though, I'd prefer not to make
use of it so the routines would work in older bashes.

So main question, I suppose is why does bash prevent using
declare in front of a function (or predeclaring it and using
the '-f' form).

older bashes might work.

reply via email to

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