首页 > 解决方案 > 为什么变量BASH_ARGV在函数中的值不同,取决于调用函数前是否使用

问题描述

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

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

#!/bin/bash

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

existArg

执行:

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

结果: Args#: 0

第二个脚本 dd.stackoverflow2.sh:

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

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

existArg

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

结果: Args#: 7

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

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

标签: bashfunctionshellenvironment-variablesarguments

解决方案


来自 bash 手册:

BASH_ARGV

[...] shell仅在扩展调试模式下设置 BASH_ARGV (有关 shopt 内置的 extdebug 选项的描述,请参见 Shopt Builtin)。在 shell 开始执行脚本后设置 extdebug,或者在未设置 extdebug 时引用此变量,可能会导致值不一致。

从 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. */

推荐阅读