It's time for one of your Bash-coded applications to write a bit of content to the console, or perhaps a filesystem. How do you do so?
Most of us learn echo early in our Bash careers. echo is so capable that it's possible to code successfully for years without touching
on printf as an alternative to echo. What's
the point of the latter, then? Is one just like the other, with a default terminal newline? Do experienced coders have any reason more interesting
than pretension for their frequent use of printf?
There is, in fact, more to the story. While quite a few commentators apparently believe that "... [t]he only difference ... is echo will
output an extra newline
...",
that's not the whole truth:
printfis better standardized;- The two differ especially in how they handle escape characters; and
echo's variations are large enough to constitute security surprises.
On MacOS 13.2.1, for instance, /bin/bash pops up as ... version 3.2.57 ... Modern Linux distributions tend to operate with version 5.1.4 or greater. The echo available within /bin/bash behaves differently with regard to -n in versions 3.2 and before, compared to 4.0 and later. One summary: "Applications aiming for maximum portability are strongly encouraged to use printf ..."
Also, "... printf is a preferred alternative ..."
Conclusion: the behavior of printf is more uniform
across different bash environments than is that of echo. Bluntly,
"... there's never a good reason to use echo ..."
More recent echo doesn't honor escaped characters. More specifically, S='ab\tcd\n'; echo "$S"; printf "$S"; printf %s "$S" with most
current Linuxes results in
ab\tcd\n
ab cd
ab\tcd\nwhile on MacOS one sees
ab cd
ab cd
ab\tcd\nAlthough echo can be easier, and perhaps require fewer keystrokes, to program in common cases, the examples above make it clear that
printf is more consistent and flexible across different environments.
echo's surprises are so many that its use arguably creates security hazards.
[Provide explicit example of security risk.]
Production-level Bash programming probably is best off to eschew echo entirely, in favor of printf. To repeat the conclusions above:
printf is more consistent and manageable.
However, echo is faster. On yet another hand,
if you have a production-level program [follow up with
essay on safe Bash programming?] where echo's speed advantage is consequential ... well,
you probably need a more delicate analysis
than fits in this little essay. As a starting point: don't leave home without ShellCheck [provide page on ShellCheck].
[Explain. Explain print -r ...]
[Explain. No advertising. Just documented, pertinent facts.]