4

I want to execute echo and get an output like:

$ export EVAR="-E"
$ echo "$EVAR"
-E

I have stored "-E" in a bash variable, say $EVAR. If I execute echo $EVAR, echo will print out nothing. Perhaps it thinks $EVAR is an argument -E. Quoting $EVAR inside double quote marks doesn't work either.

How can I print it out?

NOTE: I imagine there could be a solution which is ignorant on the content of $EVAR - with no analysis on the content of $EVAR, a command like echo some-arg $EVAR. Is that possible? Or should I only turn to a workround like printf?

xywang
  • 389
  • 1
  • 2
  • 12

5 Answers5

3

You could use tricks:

echo " $EVAR"
echo  -e "\055E"
echo $'\055E'

But as I said: those are tricks. The real solution is to use printf always:

$ printf '%s\n' "$EVAR"
-E
1

Per request, if you are fine with output being preceded with a blank line, test this solution yourself, on command line:

$ export EVAR="-E"
$ echo -e "\n$EVAR"

-E
  • original echo "$EVAR" gives nothing because, as you suspected, it sees -E as a recognized option of echo command.. man echo says: -E disable interpretation of backslash escapes (default)
  • so we precede it with a whitespace character, in this case a new line
  • but you cannot directly "\n", so use -e to interpret "\n"
  • of course this means if you still absolutely have the original $EVAR, you have to do something else to the output to remove the first blank line we have now introduced
clarity123
  • 3,539
1

use printf as mentioned, or enable shopt xpg_echo which gives you a close to standard echo:

echo 'hi\nthere'

hi
there

but it still won't handle a -E argument correctly. so you can write your own little standards compliant echo like:

echo()
    case  ${IFS- }  in
    (\ *) printf %b\\n "$*";;
    (*)   IFS=\ $IFS
          printf %b\\n "$*"
          IFS=${IFS#?}
    esac

...which will afterward mostly conform to a Single Unix Spec echo in every way (except that a bash printf also breaks with the standard in handling \[num]{1,3} octals for %b).

...and so...

echo -E

-E
mikeserv
  • 58,310
0

There's always

echo -e "\x2DE"

With \x2D being the hexadecimal code for "-". The "E" is simply appended afterwards.

0

You can use printf instead of echo:

$ EVAR="-E"
$ printf "%s\n" ${EVAR}
-E