Raphael Hertzog <hertzog@debian.org> writes:
On Sat, 12 Jul 2008, Raphael Geissert wrote:
As demonstrated by the following trivia[1], and also mentioned by
SUSv3, the echo built-in varies from implementation to implementation
and thus should be discouraged.
Well, you just proved that you can't rely on correct interpretation of
special escaped characters and that's true. It's not a reason to
discourage echo or echo -n in general though. That would be ridiculous
given how frequently it's used.
But it would be nice to remember that printf "" must be used if you want
to reliably use escaped characters. But here you must take care to use
"%s" for each variable expansion:
echo "a $var\n b"
is
printf "a %s\n b\n" "$var"
I realize that Policy already provides a little bit of generic advice
about writing shell scripts, so it's not like we have a particularly pure
distinction on which to stand, but unless we're going to require
particular practices via filing bugs I think putting best practices in the
devref may be better.
Policy does say by reference that echo varies. It referes to SUS, which
says:
If the first operand is -n, or if any of the operands contain a
backslash ( '\' ) character, the results are implementation-defined.
and:
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): [...]
We of course override the part about -n and require that it behave in a
particular way, but the part about backslashes remains.
It's unfortunate that SUS requires free registration; it makes it harder
to link directly to specific sections of interest.