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

1

2

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?

Conservator answered 14/10, 2021 at 13:43 Comment(0)
G
2

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. */
Grafting answered 14/10, 2021 at 13:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.