views:

646

answers:

3

I want to escape some special chars inside a string automatically. I thought of echoing that string and pipe it through some seds. This doesn't seem to work inside of backticks. So why does

echo "foo[bar]" | sed 's/\[/\\[/g'

return

foo\[bar]

but

FOO=`echo "foo[bar]" | sed 's/\[/\\[/g'` && echo $FOO

just returns

foo[bar]

?

In contrast to sed, tr works perfectly inside of backticks:

FOO=`echo "foo[bar]" | tr '[' '-' ` && echo $FOO

returns

foo-bar]
+10  A: 

How about not using backticks but use $() ?

FOO=$(echo "foo[bar]" | sed 's/\[/\\[/g') && echo $FOO

if you insist on using backticks, I think you need to extra escape all \ into double \

FOO=`echo "foo[bar]" | sed 's/\\[/\\\\[/g'` && echo $FOO
fforw
+1 for `$()` Never, ever use backticks. There are so many advantaged to using `$()`. http://mywiki.wooledge.org/BashFAQ/082
Dennis Williamson
and +1 for the comment referring to Bash FAQ 82
nos
+2  A: 

Usually, it's a case of underescaping

FOO=`echo "foo[bar]" | sed 's/\[/\\\[/g'` && echo $FOO
Michael Krelin - hacker
+2  A: 

You need to escape the backslashes between the backticks.

FOO=`echo "foo[bar]" | sed 's/\\[/\\\\[/g'` && echo $FOO

Alternatively, use $() (this is actually the recommended method).

FOO=$(echo "foo[bar]" | sed 's/\[/\\[/g') && echo $FOO
Alex Barrett
Thanks everyone!