help-bash
[Top][All Lists]
Advanced

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

Re: printf $variable inside initial parenthesis or use %s?


From: Lawrence Velázquez
Subject: Re: printf $variable inside initial parenthesis or use %s?
Date: Thu, 12 Jan 2023 01:25:48 -0500
User-agent: Cyrus-JMAP/3.7.0-alpha0-1185-g841157300a-fm-20221208.002-g84115730

On Wed, Jan 11, 2023, at 11:54 PM, Roger wrote:
> So the bottom line on the simple versus %s format, the simple method is fine 
> as 
> along the code/maintainer has explicit control over the contents of the 
> variable?

It's "fine" in the same way that it's technically "fine" to use
unquoted parameter expansions if you're absolutely certain that the
parameters will never contain globbing characters or IFS characters.
Many experienced shell programmers consider both to be code smells
and poor practice, as may linting tools like ShellCheck.

https://www.shellcheck.net/wiki/SC2059

Both are bad from a defensive programming standpoint because they
require you to remember in perpetuity that that variables need to
be treated specially, instead of preempting possible issues by using
the correct methods to begin with.


> If the variable has possibility of outside/user modification of the variable, 
> then resort to the lengthier %s format usage?

Or if the variable contains "%" or "\".

Or if it begins with "-".  (Although printf -- "$var" works here.)

Or if you want to use more than one argument.  (A command like

    printf foo bar baz

does not work like echo(1) does.)


> Think most of us know the more secure method, and the simple method provides 
> easier reading.

I disagree that it's "easier reading".  When I see

    printf %s "$var"

then I know exactly what it will do.  When I see

    printf "$var"

then I have to stop and verify that "var" is safe to (ab)use as a
format string.

But it seems to me that you've made up your mind to use the sloppy
method and are just looking to justify your decision, so go for it.


-- 
vq



reply via email to

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