Using echo Portably
Problem
You are writing a script that will run on multiple versions of Unix and Linux and you need echo to behave consistently even if it is not running on bash.
Solution
Use printf "%b"
whatever
, or test for the system and set xpg_echo
using shopt
-s xpg_echo
as needed.
If you omit the "%b"
format
string (for example, printf
whatever
), then printf
will try to interpret any % characters in
whatever
, which is probably not what you
want. The "%b"
format is an addition
to the standard printf format that will prevent
that misinterpretation and also expand backslash escape sequences in
whatever
.
Setting xpg_echo
is less
consistent since it only works on
bash. It can be effective if you are sure that
you’ll only every run under bash, and not under
sh or another similar shell that doesn’t use
xpg_echo
.
Using printf requires changes to how you
write echo
statements, but it’s
defined by POSIX and should be consistent across any POSIX shell
anywhere. Specifically, you have to write printf "%b"
instead of just echo
.
Warning
If you automatically type $b
instead of %b
you will be unhappy
because that will print a blank line, since you have specified a null
format. That is unless $b
is
actually defined, in which case the results depend on the value of
$b
. Either way, this can be a very
difficult bug to find since $b
and
%b
look very similar:
$ printf "%b" "Works" Works $ printf "$b" "Broken" $
Discussion
In some shells, built-in echo behaves differently than the external echo used on ...
Get bash Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.