ubuntu local:-n:无效选项

jqjz2hbq  于 2022-11-02  发布在  其他
关注(0)|答案(1)|浏览(230)

当使用./script执行脚本时,我会看到local:-n:无效选项
我的测试脚本:cat script

  1. # !/bin/bash
  2. declare -Ax BINS_TO_ARCH_FILE=(
  3. ["file1"]="test/file1"
  4. ["file2"]="test/file2"
  5. ["file3"]="test/file3"
  6. );
  7. function archive-bz2()
  8. {
  9. local -n DO_NOT_USE_THIS_NAME="$1";
  10. for path_to_archive in "${!DO_NOT_USE_THIS_NAME[@]}"; do
  11. echo "path_to_archive: $path_to_archive";
  12. done
  13. }
  14. archive-bz2 BINS_TO_ARCH_FILE

但是当我在一个带有

  1. bash script

它正在工作...

  1. echo $SHELL
  2. /bin/bash
  3. bash --version
  4. GNU bash, version 4.4.0(1)-release (x86_64-unknown-linux-gnu)
  5. Copyright (C) 2016 Free Software Foundation, Inc.
  6. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
  7. This is free software; you are free to change and redistribute it.
  8. There is NO WARRANTY, to the extent permitted by law.

我也用旧的bash版本测试了它,两种方式都工作得很好:(在两种方式上,local都是build in命令

  1. type local
  2. local is a shell builtin
  3. bash --version
  4. GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)
  5. Copyright (C) 2013 Free Software Foundation, Inc.
  6. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
  7. This is free software; you are free to change and redistribute it.
  8. There is NO WARRANTY, to the extent permitted by law.
o2rvlv0m

o2rvlv0m1#

这是一个老把戏,在两种情况下都对我很有效,所以我猜这一定是你发行版中的一些bug。
根据手册:-n表示DO_NOT_USE_THIS_NAME是对由$1(BINS_TO_ARCH_FILE)命名的变量的引用
这就是archive-bz2 BINS_TO_ARCH_FILE可以工作的原因,请注意缺少的$[@],这样它就可以用来向函数插入复杂的参数。
请注意,引用在两个方向上都起作用,因此函数也可以更新BINS_TO_ARCH_FILE的值,这样您就可以使用这种方式从函数中提取值,而不是有限返回。
localdeclarehttps://wiki.bash-hackers.org/commands/builtin/declare几乎相似

相关问题