echo testing:PROXY_URL=/proxyurl/proxyUrlSedEscaped=`echo $PROXY_URL | sed -e 's/[\/&]/\\&/g'`echo                     $PROXY_URL | sed -e 's/[\/&]/\\&/g'echo $proxyUrlSedEscapedecho ???The above has the following output:testing:\/proxyurl\/&proxyurl&???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\/
Strange output with command subtitution using backticks in bash script
bash;shell;quoting;command substitution
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.