bash echo "-n" 不会打印 -n?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/13258664/
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
echo "-n" will not print -n?
提问by MrDoom
Very similar to this question.
非常类似于这个问题。
I'm iterating through a few things with an automated script in BASH. Occasionally the script will come across "-n" and echo will attempt to interpret this.
我正在用 BASH 中的自动脚本迭代一些事情。有时脚本会遇到“-n”,echo 会尝试解释它。
Attempted this:
尝试了这个:
 $ POSIXLY_CORRECT=1 /bin/echo -n
and
和
 $ POSIXLY_CORRECT=1 /bin/echo "-n"
But it interpreted the argument each time.
但它每次都解释这个论点。
Then this, which works but it's possible to hit escaped characters in the strings, which is why I don't want to apply a null character to all input and use -e.
然后这可行,但有可能在字符串中命中转义字符,这就是为什么我不想将空字符应用于所有输入并使用 -e。
$ echo -e "\x00-n"
-n
printf is possible, but is to be avoided unless there are no other options (Not all machines have printf as a utility).
printf 是可能的,但除非没有其他选项,否则应避免使用(并非所有机器都将 printf 作为实用程序)。
$printf "%s" "-n"
-n
So is there a way to get echo to print "-n"?
那么有没有办法让 echo 打印“-n”?
采纳答案by rici
printfshould be a built-in in all your shells, unless some of your machines have very old shell versions. It's been a built-in in bashfor a long time. It's probably more portable than echo -e.
printf应该是所有 shell 内置的,除非你的一些机器有非常旧的 shell 版本。它已经内置bash很长时间了。它可能比echo -e.
Otherwise, there's really no way to get echooptions it cares about.
否则,真的没有办法获得echo它关心的选项。
Edit: from an answerto another similar question; avoid quoting issues with printfby using this handy no-digital-rights-retained wrapper:
编辑:来自另一个类似问题的答案;printf通过使用这个方便的不保留数字权利的包装器来避免引用问题:
ech-o() { printf "%s\n" "$*"; }
(That's ech-o, as in "without options")
(这是 ech-o,如“无选项”)
回答by vladz
What about prefixing the string with a character ("x" for instance) that gets removed on-the-fly with a cut:
用一个字符(例如“x”)作为字符串的前缀,该字符会通过剪切即时删除:
echo "x-n" | cut -c 2-
回答by djhaskin987
echo "-n" tells the shell to put '-n' as echo's first argument, character for character. Semantically, echo "-n"is the same as echo -n. Try this instead (it's a POSIX standard and should work on any shell):
echo "-n" 告诉 shell 将 '-n' 作为 echo 的第一个参数,一个字符一个字符。在语义上,echo "-n"与 相同echo -n。试试这个(它是一个 POSIX 标准,应该适用于任何 shell):
printf '%s\n' "-n"
回答by sidyll
If you invoke Bash with the name sh, it will mimic sh, where the -noption was not available to echo. I'm not sure if that fits your needs though.
如果您使用该名称调用 Bash sh,它将模仿sh,其中该-n选项不可用echo。不过,我不确定这是否符合您的需求。
$ /bin/sh -c 'echo -n'
回答by Radu R?deanu
echo "-n"will not print -nbecause -nis interpreted as an option for echo(see help echo). But you can use:
echo "-n"不会打印,-n因为-n被解释为echo(见help echo)的一个选项。但是你可以使用:
echo -e "5n"
回答by user3183018
Cheating method:
作弊方法:
echo -e  "\r-n"

