the echo nightmare...
Saturday, 22. March 2008, 19:37:26
Foo?
Bar
or
Foo\nBar?
$ cat echo-trivia.sh
#!/bin/bash
set -e
test='Foo:\n\tI do not like bar!!\n\nBar:\n\tI do not like you either'
nexpand=0
tests=0
for shell in bash dash ksh zsh posh pdksh sash; do
[ -x "/bin/$shell" ] || continue
set -x
o="$($shell <<< "echo 'Foo:\n\tI do not like bar!!\n\nBar:\n\tI do not like you either'")"
set +x
[ "$test" = "$o" ] && nexpand=$(($nexpand + 1))
tests=$(($tests + 1))
done
echo "==Trivia results=="
echo "Shells tested: $tests"
echo "Shells expandind backslashes: "$(($tests - $nexpand))
[ "$test" = "$(/bin/echo 'Foo:\n\tI do not like bar!!\n\nBar:\n\tI do not like you either')" ] && \
echo "/bin/echo does NOT expand" || echo "/bin/echo does expand"
$ bash echo-trivia.sh
++ bash
+ o='Foo:\n\tI do not like bar!!\n\nBar:\n\tI do not like you either'
+ set +x
++ dash
+ o='Foo:
I do not like bar!!
Bar:
I do not like you either'
+ set +x
++ ksh
+ o='Foo:\n\tI do not like bar!!\n\nBar:\n\tI do not like you either'
+ set +x
++ zsh
+ o='Foo:
I do not like bar!!
Bar:
I do not like you either'
+ set +x
++ posh
+ o='Foo:
I do not like bar!!
Bar:
I do not like you either'
+ set +x
++ pdksh
+ o='Foo:
I do not like bar!!
Bar:
I do not like you either'
+ set +x
==Trivia results==
Shells tested: 6
Shells expandind backslashes: 4
/bin/echo does NOT expand
Note: tabs are ruined by the blog
In other words, scripts using:
echo expecting backlashes not to be expanded are broken by 4
echo expecting backlashes to be expanded are broken by 2
echo -e expecting backlashes to be expanded are partially broken by 2
zsh, and pdksh silently ignore the -e option when specified.
What a mess...
This is why SUS recommends to use printf instead of echo.
By anonymous user, # 22. March 2008, 21:02:42
I use /bin/echo -e
By anonymous user, # 23. March 2008, 10:49:29
As Ben writes, use printf. Echo is inconsistent across shells, and should not be relied upon for anything but outputting simple text strings.
Compare http://www.opengroup.org/onlinepubs/009695399/utilities/echo.html with http://www.opengroup.org/onlinepubs/009695399/utilities/printf.html
By anonymous user, # 24. March 2008, 22:38:27