Unable to use an Array as environment variable

A bash array can not be an environment variable as environment variables may only be key-value string pairs.

You may do as the shell does with its $PATH variable, which essentially is an array of paths; turn the array into a string, delimited with some particular character not otherwise present in the values of the array:

$ arr=( aa bb cc "some string" )
$ arr=$( printf '%s:' "${arr[@]}" )
$ printf '%s\n' "$arr"
aa:bb:cc:some string:

Or neater,

arr=( aa bb cc "some string" )
arr=$( IFS=:; printf '%s' "${arr[*]}" )
export arr

The expansion of ${arr[*]} will be the elements of the arr array separated by the first character of IFS, here set to :. Note that if doing it this way, the elements of the string will be separated (not delimited) by :, which means that you would not be able to distinguish an empty element at the end, if there was one.


An alternative to passing values to a script using environment variables is (obviously?) to use the command line arguments:

arr=( aa bb cc )

./some_script "${arr[@]}"

The script would then access the passed arguments either one by one by using the positional parameters $1, $2, $3 etc, or by the use of $@:

printf 'First I got "%s"\n' "$1"
printf 'Then  I got "%s"\n' "$2"
printf 'Lastly there was "%s"\n' "$3"

for opt in "$@"; do
    printf 'I have "%s"\n' "$opt"
done

Arrays are bash specific. Environment variables are name-value pairs.

Read the specifications on environment variables, which says, in part:

The value of an environment variable is a string of characters. For a C-language program, an array of strings called the environment shall be made available when a process begins. The array is pointed to by the external variable environ, which is defined as:

extern char **environ;

These strings have the form name=value; names shall not contain the character '='.

Tags:

Linux

Shell

Bash