On Fri, Nov 04, 2022 at 01:30:16PM +0100, Alex fxmbsw7 Ratchev wrote:
> > 1) Put something like "shopt -u patsub_replacement 2>/dev/null || true"
> > at the top of your script.
> >
>
> there d be many such senselessnesses
>
> >
> > 2) Assign the result of the expansion to a temporary variable, and pass
> > the temp var to somecmd. Every. Single. Time.
> >
>
> ? i dont get that
OK. Let me offer a quick example script. It works as expected in
bash-5.1:
unicorn:~$ cat foo
#!/bin/bash
template='The best candy is clearly @CANDY@!'
candy='M&Ms'
printf '%s\n' "${template/@CANDY@/"$candy"}"
unicorn:~$ ./foo
The best candy is clearly M&Ms!
Now, let's run this script under bash-4.2:
unicorn:~$ bash-4.2 ./foo
The best candy is clearly "M&Ms"!
Uh oh! The quotes are wrong for bash-4.2. Bug #1 is filed for this issue.
As the maintainer of the script, I test a few things between bash-4.2
and bash-5.1 and I come up with this workaround:
unicorn:~$ cat foo
#!/bin/bash
template='The best candy is clearly @CANDY@!'
candy='M&Ms'
printf '%s\n' "${template/@CANDY@/$candy}" # unquote $candy to fix bug #1
unicorn:~$ bash-4.2 ./foo
The best candy is clearly M&Ms!
unicorn:~$ bash-5.1 ./foo
The best candy is clearly M&Ms!
Now it works on older systems too. Everything's fine... until bash-5.2.
unicorn:~$ bash-5.2 ./foo
The best candy is clearly M@CANDY@Ms!
The workaround for bug #1 causes bug #2 on bash-5.2. To make the script
work on all three versions of bash, we need a different workaround:
unicorn:~$ cat foo
#!/bin/bash
template='The best candy is clearly @CANDY@!'
candy='M&Ms'
message=${template/@CANDY@/"$candy"} # Work around bug #1 and #2.
printf '%s\n' "$message"
unicorn:~$ bash-4.2 ./foo
The best candy is clearly M&Ms!
unicorn:~$ bash-5.1 ./foo
The best candy is clearly M&Ms!
unicorn:~$ bash-5.2 ./foo
The best candy is clearly M&Ms!
And there you have it. You're allowed to quote "$candy" in a variable
assignment, as long as the whole parameter expansion ${...} remains
unquoted, and it'll work properly in all 3 versions. I'm using "message"
as a temporary variable, whose sole purpose is to work around this issue.