[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: insistence that format string for printf to use single quotes
From: |
Greg Wooledge |
Subject: |
Re: insistence that format string for printf to use single quotes |
Date: |
Sat, 28 Jan 2023 12:13:33 -0500 |
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.
> 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.