How to echo “$x_$y” in Bash script?

2020-01-28 09:03发布

It is very interesting that if you intend to display 0_1 with Bash using the code

x=0
y=1
echo "$x_$y"

then it will only display

1

I tried echo "$x\_$y" and it doesn't work.

How can I echo the form $x_$y? I'm going to use it on a file name string.

4条回答
我只想做你的唯一
2楼-- · 2020-01-28 09:09

This way:

$ echo "${x}_${y}"
0_1
查看更多
forever°为你锁心
3楼-- · 2020-01-28 09:19

Just to buck the trend, you can also do this:

echo $x'_'$y

You can have quoted and unquoted parts next to each other with no space between. And since ' isn't a legal character for a variable name, bash will substitute only $x. :)

查看更多
来,给爷笑一个
4楼-- · 2020-01-28 09:24

wrap it in curly braces:

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

查看更多
该账号已被封号
5楼-- · 2020-01-28 09:31

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

echo "$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.

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}"

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 :-)

查看更多
登录 后发表回答