且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何回显"$ x_ $ y";在Bash脚本中?

更新时间:2022-11-13 23:39:35

由于允许变量名中带有下划线,因此命令:

Because variable names are allowed to have underscores in them, the command:

echo "$x_$y"

试图回显${x_}(在您的情况下可能为空),然后回显${y}.这样做的原因是因为参数扩展是一个贪婪的操作-在$之后,将使用尽可能多的合法字符来形成变量名.

is trying to echo ${x_} (which is probably empty in your case) followed by ${y}. The reason for this is because parameter expansion is a greedy operation - it will take as many legal characters as possible after the $ to form a variable name.

bash联机帮助页的相关部分指出:

The relevant part of the bash manpage states:

$字符引入参数扩展,命令替换或算术扩展.

The $ character introduces parameter expansion, command substitution, or arithmetic expansion.

要扩展的参数名称或符号可以用大括号括起来,这是可选的,但用于保护要扩展的变量不受紧随其后的字符的影响,可以将其解释为名称的一部分.

The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name.

使用花括号时,匹配的结尾花括号是第一个},不会被反斜杠或带引号的字符串引起,而且也不位于嵌入式算术扩展,命令替换或参数扩展之内.

When braces are used, the matching ending brace is the first } not escaped by a backslash or within a quoted string, and not within an embedded arithmetic expansion, command substitution, or parameter expansion.

因此,解决方案是确保将_不作为第一个变量的一部分,可以使用以下方法来实现:

Hence, the solution is to ensure that the _ is not treated as part of the first variable, which can be done with:

echo "${x}_${y}"

我倾向于使用 all 这样的bash变量,甚至是像这样的独立变量:

I tend to do all my bash variables like this, even standalone ones like:

echo "${x}"

因为它更明确,而且我在过去被咬过很多次:-)

since it's more explicit, and I've been bitten so many times in the past :-)