简体   繁体   English

bash - 为什么我的变量开头的“-e”没有得到带有 echo 的输出?

[英]bash - Why does the "-e" at the beginning of my variable not get output with echo?

At the command prompt ($) I execute the commands:在命令提示符 ($) 下,我执行以下命令:

$ stupid="-a hello"
$ echo $stupid

Echo produces:回声产生:

-a hello

At the command prompt ($) I execute the commands:在命令提示符 ($) 下,我执行以下命令:

$ stupid="-e hello"
$ echo $stupid

Echo produces:回声产生:

hello

Why did the "-e" disappear?为什么“-e”消失了?

Since $stupid is unquoted, it gets processed as flag of echo and enables interpretation of backslash escapes.由于$stupid未加引号,因此它会作为echo标志进行处理并启用反斜杠转义的解释。

If you did:如果你这样做:

$ stupid="-e hello"
$ echo "$stupid"

You would see value of $stupid echoed in its entirety:你会看到$stupid价值得到了完整的回应:

-e hello

Because the resulting command after variable expansion would be因为变量扩展后的结果命令将是

echo "-e hello"

In your case however, $stupid is first expanded and then then the command is executed as:但是,在您的情况下, $stupid首先展开,然后命令执行为:

echo -e hello

It may become even more obvious if your variable value actually included an escaped character such as: foo="-e \\ttext" , try both echo $foo and echo "$foo" and see what happens.如果您的变量值实际上包含转义字符,例如: foo="-e \\ttext" ,则可能会变得更加明显,请同时尝试echo $fooecho "$foo"看看会发生什么。

Bottom line: double quoting your strings and or variable is usually the prudent thing to do.底线:双引号您的字符串和/或变量通常是谨慎的做法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM