Bash: array made from inside a sourced function won't be exported

Consider the following script, that just creates and prints arrays out of lists:

 $> cat my_script.sh
 #!/bin/sh
 function test_array {
    export list_2="ai ia"
    export list_2_array=($list_2)
    echo list_2=$list_2
    echo list_2_array=$list_2_array
 }
 export list="oi io"
 export list_array=($list)
 echo list=$list
 echo list_array=$list_array
 test_array

Sourcing the script, will yield correct values for the set variables and arrays:

 $> . my_script.sh
 list=oi io
 list_array=oi
 list_2=ai ia
 list_2_array=ai

Running the function inside the script will still yield correct values for them:

 $> test_array
 list_2=ai ia
 list_2_array=ai

However, whilst list_2 is properly set, list_2_array is nowhere:

 $> echo list_2=$list_2
 list_2=ai ia

 $> echo list_2_array=$list_2_array
 list_2_array=

I checked the autocompletion and, indeed, list_2_array is not even set.

What's the rationale behind this behaviour?

Answers


The readonly builtin has the same problem:

bash-4.4$ foo() { readonly a=(1);echo a=$a; }
bash-4.4$ foo
a=1
bash-4.4$ echo a=$a
a=

May be this is a bug, so I suggest you report this to bug-bash with the title "An array variable created by export/readonly builtins inside a function becomes a locale variable to that function unexpectedly".


Need Your Help

How do I convince mod_proxy_ajp to pass environment variables to its backend?

apache wsgi ajp

I'm trying to use Apache's mod_proxy with the AJP backend and an ajp-wsgi app server but it doesn't seem to be sending SetEnv variables to the application server.

asp.net GridView dynamic line creation with dropmenu as Textbox entry

c# asp.net gridview

I have found a dynamic gridview code that creates lines and saves the one you filled last.