Escaping single quotes in single-quoted Bash string
There are several cases where one would want to have single quote in single-quoted string. Several examples are:
- passing complex arguments to programs
- using tools that require special characters as arguments like sed
- defining aliases
Unfortunately single-quoted string cannot contain single quote, or in other words the second quote encountered is interpreted as end of string. For example
echo 'test \' 123'
is interpreted as the string test \, then 123 then opening new string. There are two approaches to achieve this.
Closing the string right before the single quote, then use escaped single quote, then open another single quoted string
That means that the above example comes to
echo 'test '\'' 123'
This effectively outputs three strings - 'test ', single quote and ' 123'. Here are some examples:
sed 's/'\''${\([0-9]*\)}'\''/\1/g'
replaces all digits strings enclosed with '${ and }' with digits only, e.g. '${5433}' -> 5433
alias funny_prompt='echo '\''$>'\'
outputs $>
Using $'string' quotation
When enclosing string in $'string' all characters preceded by backslash are replaced according to ANSI C quoting. That effectively means that \' becomes ', \" becomes " and so on. Remember that if you want to use single backslash, you have to escape it: \\. Now our examples come to:
echo $'test \' 123'
sed $'s/\'${\\([0-9]*\\)}\'/\\1/g'
alias funny_prompt=$'echo \'$>\
No comments yet
This page was last modified on 2025-01-14 18:09:27