help-bash
[Top][All Lists]
Advanced

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

Re: sed with Variable Substitution in the command


From: Alan D. Salewski
Subject: Re: sed with Variable Substitution in the command
Date: Sun, 22 Sep 2024 08:27:49 -0400
User-agent: Mutt/2.0.5 (2021-01-21)

On 2024-09-21 16:08:28, Greg Wooledge <greg@wooledge.org> spake thus:
On Sat, Sep 21, 2024 at 15:41:15 -0400, Alan D. Salewski wrote:
On 2024-09-21 13:54:41, "Alan D. Salewski" <salewski@att.net> spake thus:
[...]
> Sometimes using the braces would "look odd" to experienced shell > folks, and are omitted by convention:
>
>     echo $1 $2 $3              # looks "odd"
                                          ^^^
s/odd/normal/

>     echo "$1" "$2" "$3"        # same here, and safer in general

The first one may "look normal" if you're used to broken shell scripts, which, to be fair, the majority of shell users in the world seem to be, but it's not reliable.

Sad, but true. And that's a better answer to the implied question, "If it's so important to double-quote expansions, why do I see so much code that does not use them?"


The second one is better, but still not completely reliable.

If the goal is to write out the first three positional parameters, with no modifications, with spaces between them, and a newline at the end, then the only way to do this reliably is:

   printf '%s %s %s\n' "$1" "$2" "$3"

or, if you prefer:

   printf '%s\n' "$1 $2 $3"

Anything else runs the risk of having the shell or the echo command do something you don't want. Take a look at this command again:

   echo $1 $2 $3

If $1 is unquoted, then it will be subject to word splitting and pathname expansion by the shell. If IFS hasn't been changed, this means you'll potentially have altered whitespace in the output, or characters like * might be replaced by a whole bunch of filenames.

If echo is used, backslashes may have a special meaning, and may cause alterations of the output. Or if the first word of the $1 expansion looks like an option (e.g. -e or -n), it may be consumed by echo and not printed. Or both, or neither -- you can't predict how the echo command in any given execution environment will work.
[...]

Yep, all excellent points. My main point about the single-digit positional parameters was just that it is common to see them referenced without braces. But in my examples for that, it might have been better had I included only those with quoted arguments, and had not used echo.

--
a l a n   d.   s a l e w s k i
ads@salewski.email
salewski@att.net
https://github.com/salewski


reply via email to

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