bash: set array env variable and de-referencing it from any shell script fails

前端 未结 5 1983
余生分开走
余生分开走 2020-12-04 01:49

I set the a array as an environment variable in this manner eg. script test.sh

in test.sh

#!/bin/bash
export STRING=( \"str1\" \"str2\"         


        
相关标签:
5条回答
  • 2020-12-04 02:21

    The environment variables passed from processes to their children are unstructured strings; arrays cannot be supported. You can demonstrate this in Bash:

    export x=foo
    printenv x
    

    That outputs foo. If I now cause x to become an array

    x=(foo bar)
    printenv x
    

    We see no output (x is not exported).

    0 讨论(0)
  • 2020-12-04 02:21

    This says passing array as env variable is possible with bash script though. It works for defining and dereferencing the array in bash command, but it does not work when dereferencing from bash script (ubuntu 18.04).

    0 讨论(0)
  • 2020-12-04 02:37

    The misunderstanding is in thinking that environment variables are only used by shells - they are not. No attributes, including readonly, integer, and arrays, can be exported into the environment block. Environment variables may be read by any language, C, C++, Perl, Java, Python, PHP, and so on. They also exist on Windows.

    So, how could another language support Bash specific attributes? All environment variables are converted to strings, except in Bash where array values are not exported at all.

    Korn shell will export just the first element. ksh93 also does some exec exploitation to preserve variable attributes exported to Korn shell children.

    By the way, it is considered bad practice to use UPPERCASE for variable names, since they could collide with those used by the shell. Also, on Bash 3, the name STRING has issues when exported (fixed in Bash 4).

    0 讨论(0)
  • 2020-12-04 02:37

    You're trying to put an array into an environment variable, and environment variables can only be strings. bash doesn't have a method for properly serializing/deserializing arrays; do so manually.

    0 讨论(0)
  • 2020-12-04 02:39

    Read the fine manual, "bugs" section.

    Array variables may not (yet) be exported.

    Though, I don't know that many consider this an actual bug. Other shells that support ksh-style arrays don't allow exporting them either.

    You may pass around array definitions rather easily, through parameters or variables or the environment. It isn't usually very useful though.

    function f {
        unset -v "$2"
        typeset "$2"
        eval "${!1}"
        typeset -p "$2"
    }
    
    typeset -a a=(a b c)
    myArr=$(typeset -p a) f myArr a
    
    0 讨论(0)
提交回复
热议问题