Is it possible to echo the two-character string -n using just the echo command built into the bash shell?
I know I can do printf '%s\n' -n but was just wondering if the echo built-in is capable of outputting the string -n at all.
Is it possible to echo the two-character string -n using just the echo command built into the bash shell?
I know I can do printf '%s\n' -n but was just wondering if the echo built-in is capable of outputting the string -n at all.
Using -e and octal 55 for the -:
$ echo -e '\055n'
-n
... or octal 156 for the n, or octal for both:
$ echo -e '\055\0156'
-n
If the -e is bothering you, set the shell option xpg_echo to make echo always interpret backslash sequences (this is not usually what you want though):
$ shopt -s xpg_echo
$ echo '-\0156'
-n
The echo in bash also recognizes hexadecimal:
$ echo -e '\x2d\x6e'
-n
Thanks for all the answers. I'll add one of my own that I've just thought of:
echo -n -;echo n
Put any character before the "-n", and use the "\b" escape sequence in -e mode to erase it in the final output. The below example uses a space for the dummy character:
$ echo -e " \b-n"
-n
Explanation:
$ man echo
If -e is in effect, the following sequences are recognized:
\b backspace
This works visually for printing output to the terminal:
$ echo -e " \b-n" | tee /tmp/test
-n
$ cat /tmp/test
-n
But you may run into problems if you need to parse the output, as it does produce an invisible backspace character:
$ echo -e " \b-n" | wc -c
5
$ wc -c <<< $(echo -e " \b-n")
5
$ echo -e "--" | wc -c
3