1

I am experimenting with passing arrays to a shell script, as described in this question. I wrote a little script that is simply designed to take in the name of an array and print out the array:

#!/bin/bash
echo "$1"
echo "${!1}"
arrayVar=("${!1}")
echo "${arrayVar[1]}"

I declare an array variable in line with running my script, like so:

array=(foo bar test) ./test.sh array[@]

Output:

|array[@]         # the bars are only here to force the final blank line
|(foo bar test)
|

It seems that array, instead of actually being an array, is simply the string (foo bar test)

Even if I modify my script to echo array directly by name instead of indirectly through the positional parameter, I get the same result.

#!/bin/bash
echo "$1"
arrayVar=("${!1}")
echo $arrayVar
echo "${arrayVar[1]}"

echo $array
echo "${array[1]}"

Output:

|array[@]         # the bars are only here to force the final blank line
|(foo bar test)
|
|(foo bar test)
|

Am I simply doing something wrong, or does bash not support array assignments before a command?

TJ Smith
  • 45
  • 6

2 Answers2

2

There appears to be no support for it.

If array=(foo bar test) ./test.sh doesn't do it (array gets exported as the literal string '(foo bar test)', then

array=(foo bar test); export array; ./test.sh

should, and indeed, after exporting, bash reports the array as an exported array (x means exported):

$ declare -p array
declare -ax array='([0]="foo" [1]="bar" [2]="test")'

but this turns out to be a lie:

$ env | grep array; echo status=$?
  status=1
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142
2

Currently, bash does not support exporting arrays. This is documented in man bash:

Array variables may not (yet) be exported.

John1024
  • 109,961
  • 14
  • 137
  • 171