【问题标题】:Unable to access Associative from config file无法从配置文件访问关联
【发布时间】:2022-01-31 09:30:00
【问题描述】:

我正在使用 2 个不同的配置文件,我想将它们加载到我的脚本中。 目前我可以访问在一个文件(file.config)中声明的变量,但不能访问在另一个文件(file1.config)中声明的关联数组。我该如何配置,以便我也可以访问其他文件。

file.config 和 file1.config 与脚本位于同一目录中

Script.sh

#Base Directory
base_dir=`pwd`

Funct () {
   . $base_dir/file.config
}

Funct1 () {
   . $base_dir/file1.config
}

#Calling function to load config file(file.config)
Funct
echo $var1

#Calling function to load config file(file1.config)
Funct1
echo ${assArray1[flower]}

file.config

var1=val1
var2=val2

file1.config

declare -A assArray1
assArray1[fruit]=Mango
assArray1[flower]=Rose

输出 : val1

问题:无法打印关联数组元素 - echo ${assArray1[flower]}

【问题讨论】:

  • pwd 为您提供运行脚本时所在的目录,而不是脚本目录。
  • 由于您从不 cd 到不同的目录,您可以将. $base_dir/file.config 简化为. file.config

标签: linux bash shell ubuntu


【解决方案1】:

declare 在函数内调用 (Funct1) 使相应的变量成为该函数的局部变量。所以外面是无法访问的。

您可以简单地省略 file1.config 中的 declare - 或按照 dan 的建议使用 declare -g 来声明全局变量。

【讨论】:

  • 或者使用declare -g(全局)来明确。
猜你喜欢
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 2019-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-29
  • 2013-05-12
相关资源
最近更新 更多