Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to echo the literal string "-e" (and nothing else) in bash?

Tags:

bash

escaping

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.

like image 413
mpen Avatar asked Jan 09 '19 01:01

mpen


People also ask

How do I echo a string in Bash?

To print a string in Bash, use echo command. Provide the string as command line argument to echo command.

What is E flag in Bash?

The -e option means "if any pipeline ever ends with a non-zero ('error') exit status, terminate the script immediately". Since grep returns an exit status of 1 when it doesn't find any match, it can cause -e to terminate the script even when there wasn't a real "error".

What is echo $$ in Bash?

The echo command is used to display a line of text that is passed in as an argument. This is a bash command that is mostly used in shell scripts to output status to the screen or to a file.

How do you check if a string is present in another string in shell script?

The grep command can also be used to find strings in another string. In the following example, we are passing the string $STR as an input to grep and checking if the string $SUB is found within the input string. The command will return true or false as appropriate.


1 Answers

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.

like image 188
KamilCuk Avatar answered Nov 15 '22 08:11

KamilCuk