shell scripting advise: Don't use backslashes inside backtick quotes



I have tried to write a proper shell quoting function, like this:

quote() {
        _q=`echo x"$1" | sed -e '1s,^x,,' -e s,\',\'\\\\\\\\\'\',g`
        echo "'${_q}'"
}

It converts foo'bar into 'foo'\''bar', as well as foo_bar into 'foo_bar'.

Note how I didn't use backticks inside the echo command. I think it increases portability and may also be easier for humans to understand. But what has always made me wonder was the high number of backslashes needed in the sed expression that changes every ' into a '\''.

Now I found the answer and rewrote the function:

quote() {
	_sedexpr="s,','\\\\'',g"
        _quotestr=`echo x"$1" | sed -e '1s,^x,,' -e "${_sedexpr}"`
        echo "'${_quotestr}'"
}

The trick was to factor out the backslashes from the backticks, and---tadaaa---there are just four left. After the shell has interpreted the string literal, it is s,','\\'',g -- and this is fed to sed. This is easily explained, as opposed to my first version, which took about a month until I found out why all those backslashes have to be there.

So if you ever use backticks, please don't use backslashes inside them.

Roland



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]