bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: When to use printf instead of echo?


From: Eric Blake
Subject: Re: When to use printf instead of echo?
Date: Mon, 26 Jul 2010 15:34:04 -0600
User-agent: Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2.7) Gecko/20100720 Fedora/3.1.1-1.fc13 Lightning/1.0b2pre Mnenhy/0.8.3 Thunderbird/3.1.1

On 07/26/2010 03:27 PM, Peng Yu wrote:
> Hi,
> 
> Although echo is sufficient most of the time, my understanding is that
> printf may be better for certain situations (for example, formatting
> the width of a number). The manual doesn't explicitly mention in what
> situations it is better to use printf than to use echo.

Anywhere that you might have an argument that has a \ anywhere (in the
argument to echo itself, after shell quoting is removed) or a leading -.
 In short, anywhere where you want to be portable.

> In particular, I want to print a string that has single quote, double
> quote and dollar character. I could use " to enclose such string and
> add '\' to escape " and $ in the string. But I can't use ' in to
> enclose the string. It is still inconvenient to have too many escape
> characters. I'm wondering what is the best way to print such string.
> 
> echo "\$XX\"'" # this works.

Yes, because you are handing the five characters $ X X " ' to echo after
you remove the shell quoting.

> echo '$XX"\'' #this doesn't work.

That's because in shell quoting, '' preserves \, which means you have
the five literal characters $ X X " \ followed by an unterminated '.
And even if you properly terminated the trailing ', you would then be
passing a literal backslash to echo, which is not portable.

But if you intended to print the same string as your first example, this
works:

echo '$XX"'\'

(that is, use concatenation of '' quoting for the first four characters,
and backslash quoting for the last character).

In short, it sounds like you still haven't figured out that there is no
way to provide a ' inside '' quoting, but that there doesn't need to be
a way, because "" and \ quoting are both sufficient for the task.  But
that is an independent question from whether to use echo or printf.

-- 
Eric Blake   eblake@redhat.com    +1-801-349-2682
Libvirt virtualization library http://libvirt.org

Attachment: signature.asc
Description: OpenPGP digital signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]