为什么 9 之后的 bash 命令行参数需要大括号?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18318716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 06:18:01  来源:igfitidea点击:

Why do bash command line arguments after 9 require curly brackets?

bashshellcommand-linearguments

提问by Default

This may not be the most thought provoking question, but nevertheless has struck my curiosity. I have not been able to come across any answer (let alone a definitive one) on the web.

这可能不是最发人深省的问题,但仍然引起了我的好奇。我无法在网络上找到任何答案(更不用说确定的答案了)。

While reading Advanced Shell Scripting, I came across this sectionregarding command line positional arguments which states that anything after the the ninth argument must be surrounded by ${} (the longer form of variable referencing/substitution).

在阅读 Advanced Shell Scripting 时,我遇到了有关命令行位置参数的这一部分该部分指出第九个参数之后的任何内容都必须用 ${}(变量引用/替换的较长形式)括起来。

Simply put, why must you reference command line argument ten (and beyond) as ${10}, ${11}...instead of $10, $11, ...?

简而言之,为什么必须引用命令行参数十(及以后)作为${10}, ${11}...而不是$10, $11, ...

采纳答案by dtorgo

Specifically, your question relates to "positional parameters." Using $var instead of ${var} is shorthand in bash. In most cases it works well. Bash variables must start with a letter or underscore. It internally treats variables that start with a digit as a "positional parameter." When bash detects a positional parameter it only looks at the first digit, which is why $10 returns $1"0". By calling ${10} you are instructing bash to look at the complete variable instead of its built-in default of the first digit.

具体来说,您的问题与“位置参数”有关。使用 $var 而不是 ${var} 是 bash 中的简写。在大多数情况下,它运行良好。Bash 变量必须以字母或下划线开头。它在内部将以数字开头的变量视为“位置参数”。当 bash 检测到位置参数时,它只查看第一位数字,这就是 $10 返回 $1"0" 的原因。通过调用 ${10},您是在指示 bash 查看完整的变量,而不是它的第一个数字的内置默认值。

As to why it is this way? I have no idea. Legacy implementation which has been expanded upon is my guess. "Who would ever need more than....?"

至于为什么会这样?我不知道。已扩展的遗留实现是我的猜测。“谁会需要比……更多的东西?”