echo "testing:"
proxyUrlSedEscaped=`echo "$PROXY_URL" | sed -e 's/[\/&]/\\&/g'`
echo                     "$PROXY_URL" | sed -e 's/[\/&]/\\&/g'
echo "$proxyUrlSedEscaped"

echo "???"

The above has the following output:


Why is the last echo output different from the previous echo output?

This command works correctly via the command line: PROXY_URL="/proxyurl/"; echo "$PROXY_URL" | sed -e 's/[\/&]/\\&/g', output: \/proxyurl\/


Per the Bash manual (and POSIX too):

When the old-style backquote form of substitution is used, backslash retains its literal meaning except when followed by $, `, or \.

That means that `echo "$PROXY_URL" | sed -e 's/[\/&]/\\&/g'` results in the sed command that's executed being sed -e 's/[\/&]/\&/g', because the double backslash has been escaped into a single one. \& then makes a literal & in sed.

You can use $(...)-style command substitution instead to avoid that:

proxyUrlSedEscaped=$(echo "$PROXY_URL" | sed -e 's/[\/&]/\\&/g')

The new-style substitution allows any command with its usual interpretation.

If you must use ` then the fairly-grotesque double-escape works too:

proxyUrlSedEscaped=`echo "$PROXY_URL" | sed -e 's/[\/&]/\\\\&/g'`

That turns \\\\ into \\, which sed then turns into \ for you.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.