bug-bash
[Top][All Lists]
Advanced

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

Re: sourcing script file from inside a function doesn't work anymore


From: Greg Wooledge
Subject: Re: sourcing script file from inside a function doesn't work anymore
Date: Mon, 12 May 2014 08:11:12 -0400
User-agent: Mutt/1.4.2.3i

On Sat, May 10, 2014 at 12:22:40PM +0200, thioroup8 wrote:
> Now, I source it from inside a function: I obtain following error message:
> bash: declare: tmp: not found
> I think this problem raises in the particular case of involving array 
> variables definitions inside sourced bash script file...

>   cat << "EOF" > "${file_to_be_sourced}"
> declare -a tmp='([0]="1" [1]="2")'
> EOF

The problem is that you are using "declare" within the file-to-be-sourced.
When you source the file inside a function, Bash runs the declare command
within the context of the function, where declare has the same meaning as
"local".  Thus, it makes the variable local to the function.

If you only put tmp=(...) in the file, it works as you expect.  Which
is fine as long as you're only using normal arrays, and not associative
arrays.

If you want to declare associative arrays in this way, you'll need to
add the -g option to declare, which is available in bash 4.2 and later.
This makes the variable global instead of local.

There is unfortunately no middle ground between local and variable if
you must use "declare" (i.e. there is no way to mimic tmp=(foo bar)
to use default scoping with an associative array because you can't skip
the declare -A step on those), nor is there a way to mimic declare -g -A
in bash 4.0 or 4.1.

The only other option is to issue the declare -A outside of the function
(either in global scope, or in the outermost function where the variable
needs to be available), and then use tmp=(...) (without a declare) in
the file-to-be-sourced.



reply via email to

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