1

I want to pass an array and an associative array between bash script.

I tried to send the argument as in the example bellow, but I get the erro message:

./b.sh: line 3: ${1[@]}: bad substitution

How can I do this?

Example:

First script a.sh that call other script b.sh

a.sh

#!/usr/bin/bash -x

declare -a array=("a" "b")
declare -A associative_array
associative_array[10]="Hello world"

./b.sh "${array[@]}" $associative_array

b.sh

#!/usr/bin/bash

declare -a array="${1[@]}"
declare -A associative_array="$2"
echo "${array[@]}"
echo "${associative_array[10]}"

Ziliom Brom
  • 63
  • 1
  • 6
  • @TedLyngmo No, this was the error message. – Ziliom Brom Oct 14 '20 at 14:26
  • Sorry, I missed half your question so I deleted that comment. :-) Both arrays gets instantiated in my answer though. – Ted Lyngmo Oct 14 '20 at 14:26
  • 2
    You may consider `source ./b.sh` so that b.sh has direct access to both arrays. – Philippe Oct 14 '20 at 14:54
  • There are 122 Q/A when searching for `[bash] pass associative array` . https://stackoverflow.com/questions/5564418/exporting-an-array-in-bash-script/21941473#21941473 looks to have answers that directly relate to your problem. Please learn to search first . Good luck. – shellter Oct 14 '20 at 15:15

1 Answers1

0

This is going to be flame-bait since it uses the evil eval, but you may find it useful until a better solution comes along. Don't use it without reading Why should eval be avoided in Bash, and what should I use instead? first.

a.sh

declare -a array=("a" "b")
declare -A associative_array
associative_array[10]="Hello world"

./b.sh "$(declare -p array)" "$(declare -p associative_array)"

b.sh

eval "$1"
eval "$2"

echo "${array[@]}"
echo "${associative_array[10]}"
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108