0

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?

http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_10_02.html

For example:

#!/usr/bin/env bash

my_array="$this_is_an_env_var"
1

1 Answer 1

3
:> 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]}'
bar

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

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .