0

I am trying to store the string "-e test" in a bash variable. For some reason, it removes the "-e " part from the string. I cannot figure out how to escape this.

Test script:

var="-e test"
echo $var

Expected output:

-e test

Actual output:

test
Veda
  • 2,025
  • 1
  • 18
  • 34

1 Answers1

2

The problem is that your variable is expanded such that:

echo $var

becomes:

echo -e test

Where -e is a valid argument to echo. The variable is being stored correctly, but you're using it in a way that doesn't print it out correctly.

To ensure that there aren't unintended consequences like this, simply put quotes around the variable when using it:

echo "$var"

Which would be expanded by the shell to:

echo "-e test"
SpoonMeiser
  • 19,918
  • 8
  • 50
  • 68
  • I don't know of any versions of `echo` that do this, but in principle `echo "-e test"` could cause `echo` to try to treat "`e`", space, "`t`", "`e`", "`s`", and "`t`" all as command options (just like `ls -la` treats "`l`" and "`a`" both as options), and probably get an invalid option error. The safe and portable way to print strings that might start with "-" (and/or contain backslashes) is `printf '%s\n' "$var"`. – Gordon Davisson May 21 '19 at 14:53