help-bash
[Top][All Lists]
Advanced

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

Re: insistence that format string for printf to use single quotes


From: Kerin Millar
Subject: Re: insistence that format string for printf to use single quotes
Date: Sat, 28 Jan 2023 16:01:19 +0000

On Sat, 28 Jan 2023 02:37:37 +0100 (CET)
Hans Lonsdale <hanslonsdale@mailfence.com> wrote:

> A work mate is insisting that the format string string for printf should 
> always be enclosed by single quotes.
> And that if I want variable data in my output from printf, I should insert a 
> format specifier in the format string
>  (e.g. %s) and supply the variable ("$var") as the argument corresponding 
> that format string.
> 
> Does such insistence has any basis?

The short answer would be yes. The longer answer follows.

All of the operands conveyed to printf should be correctly quoted, if needs be. 
You may forgo quoting in the case that you are quite certain that, as a 
consequence of not quoting:

- no unintended word splitting shall occur
- no unintended pathname expansion shall occur
- the contents of the resulting word shall otherwise be unchanged

Consider the following.

$ printf '<%s>\n' %s '%s'
<%s>
<%s>

Clearly, the latter two operands are identical. From this, we may conclude that 
printf %s is no less safe than printf '%s'. Try removing the single quotes for 
the first operand, however, and observe that things veer sharply off the rails. 
That should serve as a clear indication as to why your colleague's insistence 
that the format specifier be consistently quoted might not be an unreasonable 
one.

All parameter expansions (including "$var") should be quoted, for similar 
reasons. See, also, http://mywiki.wooledge.org/Quotes.

-- 
Kerin Millar



reply via email to

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