swatso33 swatso33 - 4 months ago 11
Bash Question

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

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

I think it's working, you're just not seeing it.

$> echo -ne 'hello\r' 

will leave the cursor at the start of the line containing the 'hello'. So if your actual prompt is longer than the $> you have here, it will overwrite the output. Try this:

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