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: Wed, 11 Jan 2023 03:26:05 -0500
User-agent: Cyrus-JMAP/3.7.0-alpha0-1185-g841157300a-fm-20221208.002-g84115730

On Wed, Jan 11, 2023, at 2:59 AM, Roger wrote:
> When using builtin bash printf, which is more appropriate?
>
> printf "$var"
>
> or
>
> printf "%s" $var

The latter, unless the value of "var" is fully under your control
and has been explicitly designed to be used as a format string.

https://mywiki.wooledge.org/BashPitfalls#printf_.22.24foo.22


> My guess, since Bash builtin printf was designed for a drop-in POSIX 
> replacement for echo

Where did you get that idea?


> keep it simple and likely just use the first incantation, 
> printf "$var".

No.  If the variable contains printf specifiers then the output
will not be what you expect.


> While using %s only when fancier printing is required.

The "%s" specifier is the opposite of "fancy printing".  It causes
the corresponding argument to be output exactly as it is.


> I noticed while using the printf %s incantation, I typed double the amount of 
> quotes for ensuring proper variable expansion, while also additionally having 
> to keep track of the number of %s matched the number of variables to print.  
> So 
> the effort for typing the %s syntax seems more time consuming and is likely 
> more prone to typing mistakes.

It is also the correct method, while your preferred method is
essentially code injection.


-- 
vq



reply via email to

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