How do I print '-e' with echo?
The best solution is not to use echo
, but to use printf
instead.
printf '%s\n' -e
This works with arbitrary variables:
var=-e
printf '%s\n' "$var"
...meaning you don't need to do any special preparation/modification elsewhere in your code based on the knowledge that a value will be echo
d.
Incidentally, the POSIX shell command specification for echo
acknowledges that it is unportable as implemented, and contains a note on that subject:
It is not possible to use echo portably across all POSIX systems unless both -n (as the first argument) and escape sequences are omitted.
The printf utility can be used portably to emulate any of the traditional behaviors of the echo utility as follows (assuming that IFS has its standard value or is unset):
The historic System V echo and the requirements on XSI implementations in this volume of POSIX.1-2008 are equivalent to:
printf "%b\n" "$*"
The BSD echo is equivalent to:
if [ "X$1" = "X-n" ] then shift printf "%s" "$*" else printf "%s\n" "$*" fi
New applications are encouraged to use printf instead of echo.
(Emphasis added).
That said, on GNU systems, an alternative exists: Requesting standards-compliant behavior.
$ POSIXLY_CORRECT=1 /bin/echo -e
-e
with newline
echo -en '-e\n'
without newline
echo -e '-e\c'
with spaces around:
echo '-e ' echo ' -e'
using backspace (thanks to Joseph R.):
echo -e ' \b-e'
(it does output SPC BS - e LF, but when sent to a terminal that's rendered as
-e
as BS moves the cursor back one column to the left causing-
to overwrite the SPC)
The behaviour of bash
's echo
builtin may depend on bash version. It also depends on the environment (POSIXLY_CORRECT
, SHELLOPTS
and BASHOPTS
variables), the options (posix
, xpg_echo
), the build options and argv[0]
(sh
vs bash
). Here tested with GNU bash 4.2.53(1)
, default build, default options, empty environment, invoked as bash
. Works also with zsh 5.0.5
.
With GNU echo
's -e
with the ASCII codes for the characters:
$ /bin/echo -e '\055'e
-e
055
is the octal ASCII number for -
(see man ascii
for quick reference).