簡體   English   中英

為什么變量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 變量在這兩個腳本中的這種行為。

第一個 sript ./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

我也不明白為什么兩個腳本中的結果不一致。

拜托,有人可以向我解釋一下嗎?

從 bash 手冊:

BASH_ARGV

[...] shell僅在擴展調試模式下設置 BASH_ARGV(有關 shopt 內置的 extdebug 選項的描述,請參閱 Shopt 內置)。 在 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. */

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM