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
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.
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.
-e
plus non-empty stringIn 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.
-e
onlyIf 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.
Seriously, you're not restricted to echo
, are you?
printf '%s\n' "$var"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With