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?

5
  • 2
    printf "%s\n" "$EVAR"...
    – jasonwryan
    Dec 18, 2015 at 2:47
  • 2
    Related: Why is printf better than echo. Everything you ever wanted to know about echo. Dec 18, 2015 at 3:04
  • For an echo-only solution, would you be ok if the output always had a blank line first, followed by the contents of $EVAR?
    – clarity123
    Dec 18, 2015 at 4:13
  • @user454038 would you please give the solution?
    – xywang
    Dec 18, 2015 at 4:25
  • 1
    printf isn't a workaround; it's the only method of printing variables you should be using, period. Skip echo. See "Why is printf better than echo" as linked above.
    – Wildcard
    Dec 18, 2015 at 7:33

5 Answers 5

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
0
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
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
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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .