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: Hans Lonsdale
Subject: Re: insistence that format string for printf to use single quotes
Date: Sun, 29 Jan 2023 03:58:59 +0100 (CET)


> ----------------------------------------
> From: Greg Wooledge <greg@wooledge.org>
> Date: Jan 29, 2023, 5:13:33 AM
> To: <help-bash@gnu.org>
> Subject: Re: insistence that format string for printf to use single quotes
> 
> 
> On Sat, Jan 28, 2023 at 02:37:37AM +0100, Hans Lonsdale wrote:
> > A work mate is insisting that the format string string for printf should 
> > always be enclosed by single quotes.
> 
> As a default policy, that's sound.  There will be cases where the quotes
> may be omitted safely (e.g. when the format is just %s with nothing else),
> but it's never wrong to add them.

The insistence is about something a bit different though.  The insistence in 
that the format quoting
should be done with single quotes and never with doubled quotes.  Is such 
insistence sound?  

> 
> > 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.
> 
> That part is important, yes.  Compare and contrast:
> 
> unicorn:~$ msg='20% off today'
> unicorn:~$ printf "$msg"; echo
> 200ff today
> unicorn:~$ printf %s "$msg"; echo
> 20% off today
> 
> The first (non-option) argument of printf is always going to be
> interpreted as a format.  If you pass a variable whose contents are not
> stictly controlled, any percent signs or backslashes in that variable's
> contents could produce unexpected results.
> 
> In the case of known, static content, it can *sometimes* be safe to pass
> a string directly as printf's first argument, without a format.  For
> example,
> 
> printf "working..."
> some long job
> echo " done."
> 
> There's no problem with that one, because the static content string has
> no percents or backslashes.  You *could* add a %s format beforehand,
> if it makes you feel better, but it's not strictly needed.  It's just
> a matter of preference.
> 


-- 
Sent with https://mailfence.com  
Secure and private email



reply via email to

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