Charles
Charles

Reputation: 31

bash - Why does the "-e" at the beginning of my variable not get output with echo?

At the command prompt ($) I execute the commands:

$ stupid="-a hello"
$ echo $stupid

Echo produces:

-a hello

At the command prompt ($) I execute the commands:

$ stupid="-e hello"
$ echo $stupid

Echo produces:

hello

Why did the "-e" disappear?

Upvotes: 1

Views: 88

Answers (1)

Ondrej K.
Ondrej K.

Reputation: 9664

Since $stupid is unquoted, it gets processed as flag of echo and enables interpretation of backslash escapes.

If you did:

$ stupid="-e hello"
$ echo "$stupid"

You would see value of $stupid echoed in its entirety:

-e hello

Because the resulting command after variable expansion would be

echo "-e hello"

In your case however, $stupid is first expanded and then then the command is executed as:

echo -e hello

It may become even more obvious if your variable value actually included an escaped character such as: foo="-e \ttext", try both echo $foo and echo "$foo" and see what happens.

Bottom line: double quoting your strings and or variable is usually the prudent thing to do.

Upvotes: 6

Related Questions