2

How do I pass an array as a variable from a first bash shell script to a second script.

first.sh
#!/bin/bash
AR=('foo' 'bar' 'baz' 'bat')
sh second.sh "$AR" # foo
sh second.sh "${AR[@]}" # foo
second.sh
#!/bin/bash
ARR=$1
echo ${ARR[@]}

In both cases, the result is foo. But the result I want is foo bar baz bat.

What am I doing wrong and how do I fix it?

1

2 Answers 2

4

Use

sh second.sh "${AR[@]}"

which split the array elements in different arguments, i.e

sh second.sh "${A[0]}" "${A[1]}" "${A[2]}" ...

and in second.sh use

ARR=("$@")

to collect the command line arguments into an array.

Sign up to request clarification or add additional context in comments.

1 Comment

By convention, environment variables (PATH, EDITOR, SHELL, ...) and internal shell variables (BASH_VERSION, RANDOM, ...) are fully capitalized. All other variable names should be lowercase. Since variable names are case-sensitive, this convention avoids accidentally overriding environmental and internal variables.
1

Try changing ARR=$1 in second.sh with ARR=("$@"). $1 assumes a single variable but you need to serialize all array items.

2 Comments

Of course I did. Otherwise I wouldn't post it here

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.