Reputation: 282845
How can I echo
the literal string -e
and nothing else?
I'm trying to better understand how shell arguments are escaped.
The following commands do not work:
echo -e # prints nothing
echo '-e' # prints nothing
echo "-e" # prints nothing
echo \-e # prints nothing
echo \\-e # prints \-e
echo '\-e' # prints \-e
echo "'-e'" # prints '-e' (with quotes)
echo -- -e # prints -- -e
I can't find one that doesn't either include quotes or a leading slash.
Upvotes: 7
Views: 1567
Reputation: 123450
I'm assuming the real question is why:
A C# or Java function can never behave differently based on whether you invoked it as foo(4)
or foo(2+2)
or foo((int)16/4)
because that information is gone by the time the function runs. It can tell what you passed, but it can't tell how you passed it.
For the same reason, a command can never behave differently based on whether or how you escaped its arguments. Quoting and escaping is a how, while the resulting string argument is the what.
Here is the equivalent execlp
call of each of your attempts (echo
is builtin in bash but behaves the same):
# v-- How you passed it v-- What you passed
echo -e # execlp("echo", "echo", "-e", 0); # prints nothing
echo '-e' # execlp("echo", "echo", "-e", 0); # prints nothing
echo "-e" # execlp("echo", "echo", "-e", 0); # prints nothing
echo \-e # execlp("echo", "echo", "-e", 0); # prints nothing
echo \\-e # execlp("echo", "echo", "\\-e", 0); # prints \-e
echo '\-e' # execlp("echo", "echo", "\\-e", 0); # prints \-e
echo "'-e'" # execlp("echo", "echo", "'-e'", 0); # prints '-e' (with quotes)
echo -- -e # execlp("echo", "echo", "--", "-e", 0); # prints -- -e
As you can see, the how doesn't affect output at all. It all comes down to the what. This is why all the escaping in the world will fail to have the intended effect.
Upvotes: 3
Reputation: 103774
Another way, using awk
and a Bash C style string and a 'here string':
$ awk '1' <<< $'-e'
-e
Works without quotes (if that is your goal):
$ awk '1' <<< -e
-e
Upvotes: 0
Reputation: 140960
How to echo the literal string "-e" (and nothing else) in bash?
printf '%s\n' '-e'
printf -- '-e\n'
From man echo -e
is an option:
-e
enable interpretation of backslash escapes
From bash builtins:
echo ...
If the -e option is given, interpretation of the following backslash-escaped characters is enabled.
...
echo does not interpret -- to mean the end of options.
So echo -e
will make echo interpret -e
as a flag and print empty newline.
To print -e
you basically have to use printf
(or you can use an implementation of echo
that will allow to do that). I don't believe it is possible to print only -e
with bash echo builtin.
printf
is more portable. There are implementations of echo
which do not take -e
argument and it may work. On the net you can find various sites about echo portability issues.
Upvotes: 6