为什么变量BASH_ARGV在一个函数中有不同的值,取决于它在调用函数之前是否被使用

Why does the variable BASH_ARGV have a different value in a function, depending on whether it is used before calling the function

我不明白 BASH_ARGV 变量在这两个脚本中的行为。

第一个脚本./dd.Whosebug.sh:

#!/bin/bash

existArg() {
    echo "Args#: ${#BASH_ARGV[@]}"
}

existArg

执行:

./dd.Whosebug.sh hello1 hello2 hello3 hello4 hello5 hello6 hello7

结果: Args#: 0

第二个脚本dd.Whosebug2.sh:

#!/bin/bash
echo "${#BASH_ARGV}" > /dev/null

existArg() {
    echo "Args#: ${#BASH_ARGV[@]}"
}

existArg

执行: ./dd.Whosebug2.sh hello1 hello2 hello3 hello4 hello5 hello6 hello7

结果: Args#: 7

我也不明白为什么两个脚本的结果不一致。

拜托,有人可以给我解释一下吗?

来自 bash 手册:

BASH_ARGV

[...] The shell sets BASH_ARGV only when in extended debugging mode (see The Shopt Builtin for a description of the extdebug option to the shopt builtin). Setting extdebug after the shell has started to execute a script, or referencing this variable when extdebug is not set, may result in inconsistent values.

来自 bash 来源 variables.c https://github.com/bminor/bash/blob/f3a35a2d601a55f337f8ca02a541f8c033682247/variables.c#L1703 :

  /* Backwards compatibility: if we refer to BASH_ARGV or BASH_ARGC at the
     top level without enabling debug mode, and we don't have an instance
     of the variable set, initialize the arg arrays.
     This will already have been done if debugging_mode != 0. */