Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I echo "-e"?

Tags:

string

bash

echo

I want to echo a string that might contain the same parameters as echo. How can I do it without modifying the string?

For instance:

$ var="-e something"
$ echo $var
something

... didn't print -e

like image 491
Ricky Robinson Avatar asked Nov 15 '13 14:11

Ricky Robinson


People also ask

What is echo command used for?

Echo is a Unix/Linux command tool used for displaying lines of text or string which are passed as arguments on the command line. This is one of the basic command in linux and most commonly used in shell scripts. In this tutorial, we will look at the different options of echo command.


2 Answers

A surprisingly deep question. Since you tagged bash, I'll assume you mean bash's internal echo command, though the GNU coreutils' standalone echo command probably works similarly enough.

The gist of it is: if you really need to use echo (which would be surprising, but that's the way the question is written by now), it all depends on what exactly your string can contain.

The easy case: -e plus non-empty string

In that case, all you need to do is quote the variable before passing it to echo.

$ var="-e something"
$ echo "$var"
-e something

If the string isn't eaxctly an echo option or combination, which includes any non-option suffix, it won't be recognized as such by echo and will be printed out.

Harder: string can be -e only

If your case can reduce to just "-e", it gets trickier. One way to do it would be:

$ echo -e '\055e'
-e

(escaping the dash so it doesn't get interpreted as an option but as on octal sequence)

That's rewriting the string. It can be done automatically and non-destructively, so it feels acceptable:

$ var="-e something"
$ echo -e ${var/#-/\\055}
-e something

You noticed I'm actually using the -e option to interpret an octal sequence, so it won't work if you intended to echo -E. It will work for other options, though.

The right way

Seriously, you're not restricted to echo, are you?

printf '%s\n' "$var"
like image 159
JB. Avatar answered Sep 30 '22 13:09

JB.


The proper bash way is to use printf:

printf "%s\n" "$var"

By the way, your echo didn't work because when you run:

var="-e something"
echo $var

(without quoting $var), echo will see two arguments: -e and something. Because when echo meets -e as its first argument, it considers it's an option (this is also true for -n and -E), and so processes it as such. If you had quoted var, as shown in other answers, it would have worked.

like image 45
gniourf_gniourf Avatar answered Sep 30 '22 15:09

gniourf_gniourf