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
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
Use
printf
instead:Using just
echo "$var"
will still fail ifvar
contains just a-e
or similar. If you need to be able to print that as well, useprintf
.A surprisingly deep question. Since you tagged bash, I'll assume you mean
bash
's internalecho
command, though the GNU coreutils' standaloneecho
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 stringIn that case, all you need to do is quote the variable before passing it to
echo
.If the string isn't eaxctly an
echo
option or combination, which includes any non-option suffix, it won't be recognized as such byecho
and will be printed out.Harder: string can be
-e
onlyIf your case can reduce to just "-e", it gets trickier. One way to do it would be:
(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:
You noticed I'm actually using the
-e
option to interpret an octal sequence, so it won't work if you intended toecho -E
. It will work for other options, though.The right way
Seriously, you're not restricted to
echo
, are you?Since we're using bash, another alternative to
echo
is to simplycat
a "here string":printf
-based solutions will almost certainly be more portable though.Quote it:
If what you want is to get
echo -e
's behaviour (enable interpretation of backslash escapes), then you have to leave the$var
reference without quotes:Or use
eval
:Try the following:
Or use
printf
:Source: Why is bash swallowing -e in the front of an array at stackoverflow SE
The proper bash way is to use
printf
:By the way, your
echo
didn't work because when you run:(without quoting
$var
),echo
will see two arguments:-e
andsomething
. Because whenecho
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 quotedvar
, as shown in other answers, it would have worked.