我将全局变量数组保存到文件中:
declare -p hashTable > $File
declare -p testArray >> $File
我想将它们加载回全局变量。我在用这个:
source $File
从全局范围调用时很好,但是当它在函数内时,它会将变量作为本地加载回来。
有没有办法将它们加载到全局变量?有没有办法用-g选项保存,以便全局加载?
有两种方法:
-g
命令的declare
参数
declare -p hashTable testArray | sed 's/ -[aA]/&g/' >$File
Nota:我更喜欢在写sed
时使用$File
,而不是在阅读时。
fn() { source $File; }
declare -p hashTable testArray | sed 's/^.* -[aA] //' >$File
那么现在:
fn() { source $File; }
declare -A hashTable
declare -a testArray
fn
如果在函数范围之前声明了关联数组,并且在函数范围内没有使用declare
命令,那么这将完成这项工作。在BASH 4.2+上,您可以在函数内部源代码:
fn() {
source <(sed 's/^declare -[aA]/&g/' "$File")
}
# access your array outside the function
declare -p testArray
这个sed
将找到以declare -a
或declare -A
开头的行,并用declare -ag
替换它们,从而使所有数组成为全局数组。