bash - 为什么变量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
我也不明白为什么两个脚本的结果不一致。
拜托,有人可以向我解释一下吗?
解决方案
来自 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. */
推荐阅读
- javascript - Fantasy-land/id 是做什么的?
- node.js - 将 Unicode 文本文件数据插入数据库
- java - 获取在preferences.xml 中定义的默认值
- javascript - Javacsript + Android Webview:以编程方式单击按钮
- ios - 当表格视图滚动Swift时,文本字段变为空
- html - 逐列打印
- c# - 无法在 C# 中发送传真,状态显示为pending
- automation - 使用 G1ANT 打开 Chrome 时出现“元素不可见”错误
- android - Android WorkManager - 从 WorkManager 获取未完成的作品
- java - setter 的参数类型是否与 getter 的返回类型匹配?Bean 属性“引擎”不可写或设置方法无效