How can I print "-n" with `echo`?

If you don't want to use prinf you have a couple of of options, at least according to this SO Q&A, titled: echo “-n” will not print -n?.

This seems to be your best option:

$ echo "x-n" | cut -c 2-
-n

Or some variation:

$ echo -- '-n'|cut -d" " -f2
-n

printf

printf doesn't have this issue:

$ printf "%s\n" -n
-n

Why would you want to use echo? Use printf:

printf -- '-n\n'

Or:

printf '%s\n' -n

With echo:

echo -n

Will output -n<LF> in a UNIX conformant echo.

bash, dash, GNU or zsh echo (in their default configurations) can do it with:

echo -en '-n\n'

Or (on ASCII-based systems):

echo -e '\055n'

Zsh echo can do it with:

echo - -n

bash (but not zsh):

echo -n -; echo n

Interestingly, it is impossible to output -n with echo alone in a POSIX way (that is, more or less, portably across Unices and Unix-likes), since the behaviour if the first argument is -n or if any argument contains backslash characters is unspecified.


For historical reasons, echo doesn't do the usual kind of argument parsing where any argument that starts with - is an option except that -- signals the end of option. The echo command mostly prints its arguments unchanged, but depending on the unix variant, on the shell and on how the shell is configured, it may interpret some options (-e, -E, -n, -) and may treat backslash+character specially.

There's no portable way to print -n with echo alone. The portable way to print a string without having to worry about special characters is

printf %s -n

or more generally print %s "$somestring". If you want to print a final newline after the string, make that printf '%s\n' -n.

Tags:

Arguments

Echo