include.是
#!/bin/bash -
export gg
f() {
for i in "${gg[@]}"
do
echo $i
done
}
润.是
#!/bin/bash -
set -o nounset
. include.sh || exit 1
f
我收到这个错误
scripts/include.sh: line 5: gg[@]: unbound variable
是不是export
关键词应该使gg全球化并可在任何地方使用?如果没有,如何从include.sh
到处都可以使用gg?
UPDATE
环境:
$ cat /etc/*-release
NAME="SLES"
VERSION="11.4"
VERSION_ID="11.4"
PRETTY_NAME="SUSE Linux Enterprise Server 11 SP4"
旧版Unix shell不支持()
数组。您应该使用bash
调用脚本,它们将按预期运行。
如更新后的问题中所述,您需要在导出之前定义gg
:
gg=()
export gg
我测试了补丁,它工作正常。
如果你source
文件(相当于.
),命令在当前shell上下文中执行,因此不需要export
。但是,如果使用bash
,使用unset / empty数组将导致set -o nounset
终止脚本。为数组指定一些值:
gg=(value1 value2) #can be assigned in both run.sh and/or include.sh
f() {
for i in "${gg[@]}"; do
echo "$i"
done
}
或者使用参数扩展来处理:
f() {
for i in ${gg[@]+"${gg[@]}"}; do
echo "$i"
done
}
${parameter+word}
只有在设置word
时才会扩展到parameter
,否则什么都不会被替换。如果你想了解更多关于它如何与数组一起工作:wiki.bash-hackers.org。
正如@CharlesDuffy所提到的,在bash 4.4
中,空数组不会成为错误。即使没有分配array=()
也没有错误。有关更多信息,请参阅:BashFAQ #112。