bash's echo command is broken

Published: 02 December 2022
on channel: Computing: the Details
100,807
5.8k

Support me on Patreon:   / computingthedetails  
This video in blog form: http://computingthedetails.org/blog/e...

Bash's echo command is broken. You can't reliably print variable contents using echo.

This video explores how it's broken, and some things you can do to work around it.
There's even a demo of a bug in some other software caused by the strange behaviour of echo.

!!! Spoilers for the challenge below !!!

At the end of the video is this challenge:

make bash's echo print "-n" with no other characters, not even the newline, without using any other commands, without piping the output anywhere.

Some things people often try that don't work:

echo -n - -n
echo -n -- -n

unix commands often interpret a "-" or a "--" as "don't process any further arguments as options to the command, but as something less special". echo in bash does not do this. The first option above does work for zsh though, so points to zsh for making that work. The second option in that list works for fish, which imho has the most sensible and predictable echo implementation. Neither works for bash. bash just prints those dashes.

The things that do work for bash are as follows:

echo -en '\u002dn'
echo -e '-n\c'

The first option there uses an escape sequence to generate the dash, which is not interpreted at option parsing time, but comes much later, thus preventing bash interpreting it as an option.

The second one uses a very special escape sequence, "\c", which means "stop outputting at this point". Since "\" is not a valid echo option, the argument is not interpreted as special. It does not appear in the output, because it is the "stop now" escape sequence, therefore you just get the "-n".

You might be tempted to use the '\c' trick to try and enable reliable printing of variables, but actually this doesn't work. For example, the following might be tempting at first:

echo -e "$VAR\n\c"

But remember that the "-e" means anything in VAR that looks like an escape sequence is now going to be interpreted by echo, and so the variable won't be printed correctly.


On this page of the site you can watch the video online bash's echo command is broken with a duration of hours minute second in good quality, which was uploaded by the user Computing: the Details 02 December 2022, share the link with friends and acquaintances, this video has already been watched 100,807 times on youtube and it was liked by 5.8 thousand viewers. Enjoy your viewing!