Is there a way to pass a string value as env variable and have bash recognize it as an array? In other words, is there some special string format that tells bash that the string is an array? Or is otherwise array-like?


For example:

#!/usr/bin/env bash


1 Answer 1

:> export ar=(foo bar baz) # create and "export" array
:> bash -c 'echo ${ar[1]}' # array is not visible in a regular child process

:> declare -p ar           # get a string which correctly creates the array
declare -a ar=([0]="foo" [1]="bar" [2]="baz")
:> my_array="$(declare -p ar)" bash -c 'eval "$my_array";echo ${ar[1]}'

The eval turns the string variable into an array variable. eval should only be used with trusted data sources, though.

  • 1
    @ilkkachu That should be enough. Dec 23, 2017 at 17:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.