bash:设置数组 env 变量并从任何 shell 脚本中取消引用它失败 [英] bash: set array env variable and de-referencing it from any shell script fails

查看:15
本文介绍了bash:设置数组 env 变量并从任何 shell 脚本中取消引用它失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以这种方式将a数组设置为环境变量例如.脚本 test.sh

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

在 test.sh 中

in test.sh

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

source test.sh

source test.sh

现在在脚本中 test-1.sh

#!/bin/bash
echo ${STRING[0]}

响应什么都没有,只是一个空行,而如果我尝试在 test.sh 中设置 STRING="str1"并在 test-1.sh 中执行 echo $STRING,这样就可以了.

the response is nothing, just a blank line, whereas, if I try to set STRING="str1" in test.sh and do echo $STRING in test-1.sh, this works.

测试仅从 root 用户执行,现在如何将数组设置为环境变量,以便我可以根据需要调用数组的元素?早些时候,我什至尝试修改 /etc/bashrc 也没有产生任何积极的结果.

tests are executed from root user only, Now how to set array as env variable , so that I can call the elements of array as per requirement? Earlier, I have tried to even modify /etc/bashrc and that also didn't result in anything positive.

我需要将数组设置为 env 变量,因为我可能需要编写许多脚本来使用这些变量设置.

I need to set the array as env variable as there may be many scripts that i have to write which shall use these variable settings.

谁能给我建议来纠正我做错的地方?

can anybody provide me suggestions to correct me where I am doing wrong?

推荐答案

阅读精美手册,bugs"部分.

Read the fine manual, "bugs" section.

数组变量可能(尚未)被导出.

Array variables may not (yet) be exported.

不过,我不知道有多少人认为这是一个实际的错误.其他支持 ksh 样式数组的 shell 也不允许导出它们.

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

这篇关于bash:设置数组 env 变量并从任何 shell 脚本中取消引用它失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆