plhn
plhn

Reputation: 5263

assinging "-n" string to a variable doesn't work

$ OPTION="-n"
$ echo $OPTION
$

Nothing happens. I expected this.

$ OPTION="-n"
$ echo $OPTION
-n
$

Why is this?

Upvotes: 2

Views: 137

Answers (3)

David W.
David W.

Reputation: 107040

Remember that the shell expands environment variables before the command is executed. Thus:

option="-n"
echo $option

becomes

echo -n ""

With the value of $option being interpreted as a parameter for the echo command. If you were using Kornshell (which is 95% similar to BASH), you could have used the builtin print command instead:

option="-n"
print -- "$option"

Unfortunately, BASH doesn't have the print command, and using the double dash in the BASH echo command will print out a double dash -- not what you want.

Instead, you'll have to use the printf command which is a bit slower than echo:

option="-n"
printf -- "$option\n"  #Must include the \n to make a new line!

Of course, if you had this, you'd be in trouble:

option="%d"
printf -- "$option\n"

To get around that:

option="%d"
printf "%s\n", "$option"

By the way, you have the same problems with test:

option="-n"
if [ "$option" -eq "-n" ]   #Won't work!

This is why you'll see people do this:

if [ "x$option" -eq "x-n" ] #Will work

Upvotes: 2

Kim Stebel
Kim Stebel

Reputation: 42037

To get the desired result, you could do this:

$ OUTPUT='-n'
$ echo -en ${OUTPUT}\\n

Upvotes: 0

David Yaw
David Yaw

Reputation: 27864

-n is a parameter to echo, which means the trailing newline is suppressed. The fact that there's no empty line between $ echo $OPTION and the following $ means that $OPTION is properly set to -n.

If you put something else in front of $OPTION, the echo will work as you expect it to. echo only interprets words at the beginning of the command as options. As soon as it finds a non-option word ("OPTION", in this case), all words that follow are treated as literals, and not parsed as options to echo.

$ echo OPTION is set to $OPTION
OPTION is set to -n
$

Upvotes: 5

Related Questions