Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quotes in Bash pattern substitution variable expansion

Tags:

bash

Should I quote variables when performing Bash parameter expansion?

For example in the following, should "${E}" be in quotes?

(
E="-END"

X=(ABC 123 "ABC 123")
X=("${X[@]/%/"${E}"}")

IFS=$'\n'
echo "${X[*]}"
)

I've noticed on 4.2 versions of bash this will result in the following output

ABC"-END"
123"-END"
ABC 123"-END"

But on 4.3 versions of bash this will result in the following output

ABC-END
123-END
ABC 123-END

Is this a bug that was fixed?

Edit. Changed "$E" to "${E}"

like image 381
Jon Avatar asked Feb 18 '26 09:02

Jon


1 Answers

This is not a bug, but documented in the official change log:

This document details the changes between this version, bash-4.3-alpha, and the previous version, bash-4.2-release.

...

zz. When using the pattern substitution word expansion, bash now runs the replacement string through quote removal, since it allows quotes in that string to act as escape characters. This is not backwards compatible, so it can be disabled by setting the bash compatibility mode to 4.2.

To toggle compatibility mode (if you want to experiment):

shopt -s compat42

and you'll see that 4.3 behaves like 4.2, and to unset it:

shopt -u compat42
like image 185
gniourf_gniourf Avatar answered Feb 20 '26 23:02

gniourf_gniourf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!