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"
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
    @ilkkachu That should be enough. – Hauke Laging Dec 23 '17 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.