1

In Bash (or really any other shell), if I have an arbitrary string that I want to echo, how can I make it so the echo doesn't come out empty if the string is -n, -e, or -E? I would expect something like echo -- -e to work (stopping echo from interpreting any further options), but it doesn't.

Even explicitly specifying a flag doesn't stop it: echo -E -en still gives no output.

Is it possible to be safe when using echo, or do I just have to switch all my echo calls to printf '%s\n'?

Stuart P. Bentley
  • 10,195
  • 10
  • 55
  • 84

2 Answers2

4

I'd use:

printf "%s\n" "-n"

It's simple, safe, reliable, and available most places these days.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
2

Kinda ugly, but this seems to work:

echo -e "-\0e"

Edit: As suggested by glglgl in the comments, a better solution is

echo -e '-\0145' or echo -e '-\x65'

Malt
  • 28,965
  • 9
  • 65
  • 105
  • 1
    It only looks as if it would do. `echo -e "-\0e"|hexdump -C` gives me `00000000 2d 00 65 0a`. The `00` is unwanted here. But `echo -e '-\0145'` should do, `0145` being the octal representation of `e`. – glglgl Aug 07 '14 at 08:03
  • fair point. I'll update the answer. – Malt Aug 07 '14 at 08:09