How to make echo interpret backslash escapes and not print a trailing newline?

seanwatson picture seanwatson · May 14, 2012 · Viewed 40k times · Source

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
$>

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$>

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'
$>

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

Answer

Mark Reed picture Mark Reed · May 14, 2012

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

$> echo -ne 'hello\r' 

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'

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'