当使用./script
执行脚本时,我会看到local:-n:无效选项
我的测试脚本:cat script
个
# !/bin/bash
declare -Ax BINS_TO_ARCH_FILE=(
["file1"]="test/file1"
["file2"]="test/file2"
["file3"]="test/file3"
);
function archive-bz2()
{
local -n DO_NOT_USE_THIS_NAME="$1";
for path_to_archive in "${!DO_NOT_USE_THIS_NAME[@]}"; do
echo "path_to_archive: $path_to_archive";
done
}
archive-bz2 BINS_TO_ARCH_FILE
但是当我在一个带有
bash script
它正在工作...
echo $SHELL
/bin/bash
bash --version
GNU bash, version 4.4.0(1)-release (x86_64-unknown-linux-gnu)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
我也用旧的bash版本测试了它,两种方式都工作得很好:(在两种方式上,local都是build in命令
type local
local is a shell builtin
bash --version
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
Copyright (C) 2013 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
1条答案
按热度按时间o2rvlv0m1#
这是一个老把戏,在两种情况下都对我很有效,所以我猜这一定是你发行版中的一些bug。
根据手册:
-n
表示DO_NOT_USE_THIS_NAME
是对由$1(BINS_TO_ARCH_FILE
)命名的变量的引用这就是
archive-bz2 BINS_TO_ARCH_FILE
可以工作的原因,请注意缺少的$
和[@]
,这样它就可以用来向函数插入复杂的参数。请注意,引用在两个方向上都起作用,因此函数也可以更新
BINS_TO_ARCH_FILE
的值,这样您就可以使用这种方式从函数中提取值,而不是有限返回。local
与declare
https://wiki.bash-hackers.org/commands/builtin/declare几乎相似