Let\'s say, you have a Bash alias
like:
alias rxvt=\'urxvt\'
which works fine.
However:
shell_escape () {
printf '%s' "'${1//\'/\'\\\'\'}'"
}
Implementation explanation:
double quotes so we can easily output wrapping single quotes and use the ${...}
syntax
bash's search and replace looks like: ${varname//search/replacement}
we're replacing '
with '\''
'\''
encodes a single '
like so:
'
ends the single quoting
\'
encodes a '
(the backslash is needed because we're not inside quotes)
'
starts up single quoting again
bash automatically concatenates strings with no white space between
there's a \
before every \
and '
because that's the escaping rules for ${...//.../...}
.
string="That's "'#@$*&^`(@#'
echo "original: $string"
echo "encoded: $(shell_escape "$string")"
echo "expanded: $(bash -c "echo $(shell_escape "$string")")"
P.S. Always encode to single quoted strings because they are way simpler than double quoted strings.