Bash:以“-”开头的回显字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3652524/
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-17 22:35:16  来源:igfitidea点击:

Bash: echo string that starts with "-"

bashscriptingshell

提问by miracle2k

VAR="-e xyz"
echo $VAR

This prints xyz, for some reason. I don't seem to be able to find a way to get a string to start with -e.

xyz出于某种原因,这会打印。我似乎无法找到一种方法来让字符串以-e.

What is going on here?

这里发生了什么?

采纳答案by heb

The variable VARcontains -e xyz, if you access the variable via $the -eis interpreted as a command-line option for echo. Note that the content of $VARis not wrapped into ""automatically.

变量VAR包含-e xyz,如果您通过 访问变量$-e则被解释为 的命令行选项echo。请注意, 的内容$VAR不会""自动包装到。

Use echo "$VAR"to fix your problem.

使用echo "$VAR"解决您的问题。

回答by camh

The answers that say to put $VARin quotes are only correct by side effect. That is, when put in quotes, echo(1)receives a single argument of -e xyz, and since that is not a valid option string, echojust prints it out. It is a side effect as echocould just as easily print an error regarding malformed options. Most programs will do this, but it seems GNU echo(from coreutils) and the version built into bashsimply echo strings that start with a hyphen but are not valid argument strings. This behaviour is not documented so it should not be relied upon.

说要加$VAR引号的答案仅在副作用方面是正确的。也就是说,当放在引号中时,echo(1)接收 的单个参数-e xyz,并且由于这不是有效的选项字符串,echo只需将其打印出来。这是一个副作用,echo因为它很容易打印有关格式错误的选项的错误。大多数程序都会这样做,但似乎 GNU echo(from coreutils) 和内置的版本bash只是简单地回显以连字符开头但不是有效参数字符串的字符串。此行为未记录在案,因此不应依赖它。

Further, if $VARcontains a valid echooption argument, then quoting $VAR will not help:

此外,如果$VAR包含有效的echo选项参数,则引用 $VAR 将无济于事:

$ VAR="-e"
$ echo "$VAR"

$

Most GNU programs take --as an argument to mean no more option processing — all the arguments after --are to be processed as non-option arguments. bash echodoes not support this so you cannot use it. Even if it did, it would not be portable. echohas other portability issues (-nvs \c, no -e).

大多数 GNU 程序将--参数作为参数表示不再进行选项处理——后面的所有参数--都将作为非选项参数进行处理。bash echo不支持这个所以你不能使用它。即使这样做了,它也不是便携式的。echo有其他可移植性问题(-nvs \c, no -e)。

The correct and portable solution is to use printf(1).

正确且可移植的解决方案是使用printf(1).

printf "%s\n" "$VAR"

回答by adamk

Try:

尝试:

echo "$VAR"

instead.

反而。

(-eis a valid option for echo- this is what causes this phenomenon).

-e是一个有效的选项echo- 这就是导致这种现象的原因)。

回答by msw

The -eis being interpreted by bash as an argument to echo. Try

-e正在被bash的解释作为参数来呼应。尝试

echo "$VAR"