dobordx
dobordx

Reputation: 19

Why '&' has special meaning in bash string-replace since bash 5.2

Why does bash make an additional and unnecessary substitution & for the word that was replaced when replacing a substring?

Test replace string in bash:

test="test string MARKER end"; echo "${test/MARKER/new value '&' why & in new value was replaced}"

I've got output:

test string new value & why MARKER in new value was replaced end

why is there a MARKER here again?

Upvotes: 1

Views: 72

Answers (1)

Guillaume Outters
Guillaume Outters

Reputation: 1707

"unnecessary" is your first feeling; but in fact it can be quite useful when you want to include the matched string in the output, without certainty about the matched string.

In your example you don't have uncertainty (you know you are looking for the fixed string "MARKER"),
but let's take another example where the match is polymorphic:

prices="12.34 € + $ 9.45"
echo ${prices//[€$]/(&)} # "Either an euro, or a dollar"
# prints: 12.34 (€) + ($) 9.45

Here I knew I wanted the replaced string to be part of the replacement (between two parenthesis), but I did't know in advance if it would be an euro or a dollar.

With the & I make sure the replacement reproduces the matched string.

Upvotes: 6

Related Questions