Home > OS >  Why does the variable BASH_ARGV have a different value in a function, depending on whether it is use
Why does the variable BASH_ARGV have a different value in a function, depending on whether it is use

Time:10-15

I don't understand this behavior that the BASH_ARGV variable has in these two scripts.

First sript ./dd.stackoverflow.sh:

#!/bin/bash

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

existArg

Execución:

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

Result: Args#: 0

Second script dd.stackoverflow2.sh:

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

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

existArg

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

Result: Args#: 7

I also don't understand why the result is not consistent in both scripts.

Please, can someone explain this to me?

CodePudding user response:

From bash manual:

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.

From bash sources 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. */
  • Related