PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 22, 2022

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

 August 22, 2022     arguments, bash, environment-variables, function, shell     No comments   

Issue

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?


Solution

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


Answered By - KamilCuk
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing