如何使echo解释反斜杠转义符而不打印尾随换行符? [英] How to make echo interpret backslash escapes and not print a trailing newline?

查看:375
本文介绍了如何使echo解释反斜杠转义符而不打印尾随换行符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在bash中使用 echo 来打印出一个字符串,然后只返回一个回车符。我浏览了手册页,发现 echo -e 将使 echo 解释反斜杠转义字符。使用它,我可以说 echo -e'hello\r',它将像这样打印

I would like to use echo in bash to print out a string of characters followed by only a carriage return. I've looked through the man page and have found that echo -e will make echo interpret backslash escape characters. Using that I can say echo -e 'hello\r' and it will print like this

$>echo -e 'hello\r'
 hello
$>

因此,看起来它已正确处理了回车。我还发现手册页中的 echo -n 会阻止 echo 插入换行符,并且看起来可行当我这样做

So it looks like it handled the carriage return properly. I also found echo -n in the man page will stop echo from inserting a newline character and it looks like it works when I do this

$>echo -n 'hello\r'
 hello\r$>

我遇到的问题是同时合并两个 -e -n 。我已经尝试过每个 echo -e -n'hello\r' echo -n -e'hello\r' code>, echo -en'hello\r' echo -ne'hello\r'并不会像这样打印任何内容:

The problem I'm having is in combining both -e and -n. I've tried each of echo -e -n 'hello\r', echo -n -e 'hello\r', echo -en 'hello\r', and echo -ne 'hello\r' and nothing gets printed like so:

$>echo -ne 'hello\r'
$>

这里是否缺少我的东西,或者 -e -n 选项不能一起使用吗?

Is there something I'm missing here or can the -e and -n options not be used together?

推荐答案

我认为它正在运行,您只是看不到它。这是您的命令:

I think it's working, you're just not seeing it. This is your command:

$> echo -ne 'hello\r' 

由于回车( \r ),它将光标停留在写 hello 的终端的同一行的开头-这就是输出到终端的下一个内容将被写入。因此,如果实际提示的时间长于此处显示的 $> ,它将完全覆盖 hello

Because of the carriage return (\r), that will leave the cursor at the start of the same line on the terminal where it wrote the hello - which means that's where the next thing output to the terminal will be written. So if your actual prompt is longer than the $> you show here, it will overwrite the hello completely.

此序列将使您看到实际发生的情况:

This sequence will let you see what's actually happening:

echo -ne 'hello\r'; sleep 5; echo 'good-bye'

但是为了更好地移植到其他shell,我会避免在 echo 这样。这些纯粹是bashisms,POSIX标准不支持。但是,内置的 printf 由POSIX指定。因此,如果要显示没有换行符的字符串并分析反斜杠序列,则可以使用它:

But for better portability to other shells, I would avoid using options on echo like that. Those are purely bashisms, not supported by the POSIX standard. The printf builtin, however, is specified by POSIX. So if you want to display strings with no newline and parsing of backslash sequences, you can just use it:

printf '%s\r' 'hello'

这篇关于如何使echo解释反斜杠转义符而不打印尾随换行符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆