Bash从文件中保存并加载数组

问题描述 投票:0回答:2

我将全局变量数组保存到文件中:

declare -p hashTable  > $File
declare -p testArray >> $File

我想将它们加载回全局变量。我在用这个:

source $File

从全局范围调用时很好,但是当它在函数内时,它会将变量作为本地加载回来。

有没有办法将它们加载到全局变量?有没有办法用-g选项保存,以便全局加载?

bash
2个回答
1
投票

My two cents:

有两种方法:

  1. 使用-g命令的declare参数 declare -p hashTable testArray | sed 's/ -[aA]/&g/' >$File Nota:我更喜欢在写sed时使用$File,而不是在阅读时。 fn() { source $File; }
  2. 将全局变量声明为超出函数范围: declare -p hashTable testArray | sed 's/^.* -[aA] //' >$File 那么现在: fn() { source $File; } declare -A hashTable declare -a testArray fn 如果在函数范围之前声明了关联数组,并且在函数范围内没有使用declare命令,那么这将完成这项工作。

2
投票

在BASH 4.2+上,您可以在函数内部源代码:

fn() {
   source <(sed 's/^declare -[aA]/&g/' "$File")
}

# access your array outside the function
declare -p testArray

这个sed将找到以declare -adeclare -A开头的行,并用declare -ag替换它们,从而使所有数组成为全局数组。

© www.soinside.com 2019 - 2024. All rights reserved.