Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

echo

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?

like image 220
seanwatson Avatar asked May 14 '12 01:05

seanwatson


People also ask

How do you echo a backslash in Shell?

The backslash (\) character is used to mark these special characters so that they are not interpreted by the shell, but passed on to the command being run (for example, echo ). So to output the string: (Assuming that the value of $X is 5): A quote is ", backslash is \, backtick is `. A few spaces are and dollar is $.


2 Answers

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'
like image 67
Mark Reed Avatar answered Sep 17 '22 11:09

Mark Reed


There are numerous different implementations of the echo command. There's one built into most shells (with different behavior for each), and the behavior of /bin/echo varies considerably from one system to another.

Rather than echo, use printf. It's built into bash as well as being available as an external command, and its behavior is much more consistent across implementations. (The major variation is that the GNU coreutils printf recognizes --help and --version options.)

Just use:

printf 'hello\r'
like image 22
Keith Thompson Avatar answered Sep 19 '22 11:09

Keith Thompson