本文共 2241 字,大约阅读时间需要 7 分钟。
本文翻译自:
I have a problem with echo
in my script: 我的脚本中存在echo
问题:
echo -n "Some string..."
prints 版画
-n Some string...
and moves to the next line. 并移至下一行。 In the console it's working correcly without newline: 在控制台中,它不需要换行就可以正常工作:
Some string...
参考:
There are multiple versions of the echo
command, with different behaviors. echo
命令有多个版本,具有不同的行为。 Apparently the shell used for your script uses a version that doesn't recognize -n
. 显然,用于脚本的外壳程序使用的版本无法识别-n
。
The printf
command has much more consistent behavior. printf
命令具有更一致的行为。 echo
is fine for simple things like echo hello
, but I suggest using printf
for anything more complicated. echo
适用于诸如echo hello
类的简单事情,但我建议将printf
用于更复杂的事情。
What system are you on, and what shell does your script use? 您在什么系统上,脚本使用什么外壳?
Try with 试试看
echo -e "Some string...\c"
It works for me as expected (as I understood from your question). 正如我从您的问题中了解到的那样,它对我有效。
Note that I got this information from the man
page. 请注意,我是从man
页获得此信息的。 The man
page also notes the shell may have its own version of echo
, and I am not sure if bash
has its own version. man
页还指出,shell可能具有自己的echo
版本,并且我不确定bash
是否具有自己的版本。
bash
has a "built-in" command called "echo": bash
有一个名为“ echo”的“内置”命令:
$ type echoecho is a shell builtin
Additionally, there is an "echo" command that is a proper executable (that is, the shell forks and execs /bin/echo
, as opposed to interpreting echo
and executing it): 此外,还有一个“ echo”命令,该命令是适当的可执行文件(即,与解释和执行echo
相反,shell派生和execs /bin/echo
):
$ ls -l /bin/echo-rwxr-xr-x 1 root root 22856 Jul 21 2011 /bin/echo
The behavior of either echo
's WRT to \\c
and -n
varies. echo
的WRT到\\c
和-n
各不相同。 Your best bet is to use printf
, which is available on four different *NIX flavors that I looked at: 最好的选择是使用printf
,它在我看过的四种不同的* NIX风格中可用:
$ printf "a line without trailing linefeed"$ printf "a line with trailing linefeed\n"
如果您在if命令中与其他命令(例如“ read”)一起使用echo,则它可能会忽略该设置,并且无论如何都会跳到新行。
Just for the Ubuntu
& it's bash
: 仅适用于 Ubuntu
& bash
:
Check which shell are you using? 检查您使用的是哪个外壳? Mostly below works, else : 大多在下面的作品,否则 :
echo $0
If above prints bash
, then below will work: 如果上面打印bash
,那么下面的将起作用:
printf "hello with no new line printed at end"
echo -n "hello with no new line printed at end"
转载地址:http://kpcnb.baihongyu.com/