1

I'm trying to assign -e to a variable in Bash 4. But the variable remains empty.

For example:

$ var="-e" 
$ echo $var

$ var='-e' 
$ echo $var

$ var="-t" 
$ echo $var
-t

Why does it work with -t, but not -e?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250
Dude
  • 73
  • 5
  • 1
    Outputting the variable with `echo` would output nothing, but the variable has the value `-e` (which is a valid option for `echo` in `bash`). You'd have the same issue with `-n` and `-E` and combinations thereof. – Kusalananda Aug 25 '19 at 07:43

2 Answers2

5

It works, but running echo -e doesn't output anything in Bash unless both the posix and xpg_echo options are enabled, as the -e is then interpreted as an option:

$ help echo
echo: echo [-neE] [arg ...]
    Write arguments to the standard output.

    Display the ARGs, separated by a single space character and followed by a
    newline, on the standard output.

    Options:
      -n        do not append a newline
      -e        enable interpretation of the following backslash escapes
      -E        explicitly suppress interpretation of backslash escapes

Use

printf "%s\n" "$var"

instead.

And as cas notes in a comment, Bash's declare -p var (typeset -p var in ksh, zsh and yash (and bash)) can be used to tell the exact type and contents of a variable.

See: Why is printf better than echo?

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
ilkkachu
  • 133,243
  • 15
  • 236
  • 397
  • 1
    also, if the OP wants to verify that $var does indeed contain `-e`, they can run `declare -p var`. – cas Aug 25 '19 at 07:54
0

A command (like your echo) takes command line arguments which could be flags (-e in your case). Many commands (at least common Linux versions) understand -- (two hyphens) as "end of flags, whatever follows is regular arguments". So you can delete a file perversely named -r by rm -- -r.

For displaying stuff, printf is more robust all around (if harder to use).

vonbrand
  • 18,156
  • 2
  • 37
  • 59