On 2026-11-16 13:42:34 +0100, Nicolas George wrote:
> Vincent Lefevre (HE12026-11-16):
> > Yes, but AFAIK, this is valid. At least code like
> >   printf "...\n"
> > is very common in shell scripts (including /bin/sh ones).
> 
> Using echo -n is quite common too. I thought you were arguing for
> something as standard and robust as possible. Nothing that relies on a
> comprehensive list of special characters is robust.
> 
> Can you tell, without looking at the standard, the exact list of
> characters in front of which backslash is an escaping character rather
> than the character backslash itself? And can you tel, for most common
> implementations of the shell, if they conform to the standard?

I would have said that backslash + ASCII letter ([A-Za-z]) inside
double quotes is safe (probably with digits too) as used in many
scripts, and such characters are obviously not characters that need
escaping. This should really be standardized if not done yet.

On 2026-11-16 07:54:18 -0500, Greg Wooledge wrote:
> On Mon, Nov 16, 2026 at 13:34:09 +0100, Vincent Lefevre wrote:
> > On 2026-11-16 12:44:55 +0100, Nicolas George wrote:
> > > The escaping if fragile, it relies on the fact that a is not a special
> > > character for escaping and therefore the backslash in front of it will
> > > not have its special semantic.
> > 
> > Yes, but AFAIK, this is valid. At least code like
> > 
> >   printf "...\n"
> > 
> > is very common in shell scripts (including /bin/sh ones).
> 
> It's technically wrong, but it works in every shell I've seen, so
> people keep using it.

And Debian (for instance) keeps distributing such scripts.

> Single quotes are preferred there, both for the \ preservation, and
> to discourage people from using expansions in the printf format
> argument.  printf "$myvar\\n" is far worse, unless myvar is tightly
> controlled and designed to be used as a printf format argument.

If the string contains the ' character, one would typically use
double quotes.

> printf '%s\n' "$myvar" is one correct way to write it.
> printf %s\\n "$myvar" is another.
> printf "%s\\n" "$myvar" is another, but I really don't recommend this one.
> 
> If you're confused about whether you should be using one \ or two \\,
> that's exactly why single quotes are recommended.  Then you always know
> you want one \, which will be passed along literally.

There are cases when one wants to be able to do expansion, knowing
that this is safe. For instance:

  printf "Exit status: $?\n"

BTW, /usr/bin/annotate-output in devscripts has similar code:

  printf "$?\n" >&2;
  err="$?"; printf "Finished with exitcode $err\n" | handler I; exit "$err";

-- 
Vincent Lefèvre <[email protected]> - Web: <https://www.vinc17.net/>
100% accessible validated (X)HTML - Blog: <https://www.vinc17.net/blog/>
Work: CR INRIA - computer arithmetic / Pascaline project (LIP, ENS-Lyon)

Reply via email to