Wednesday, August 1, 2018

bash - How to escape single quotes within single quoted strings



Let's say, you have a Bash alias like:




alias rxvt='urxvt'


which works fine.



However:



alias rxvt='urxvt -fg '#111111' -bg '#111111''



won't work, and neither will:



alias rxvt='urxvt -fg \'#111111\' -bg \'#111111\''


So how do you end up matching up opening and closing quotes inside a string once you have escaped quotes?



alias rxvt='urxvt -fg'\''#111111'\'' -bg '\''#111111'\''



seems ungainly although it would represent the same string if you're allowed to concatenate them like that.


Answer



If you really want to use single quotes in the outermost layer, remember that you can glue both kinds of quotation. Example:



 alias rxvt='urxvt -fg '"'"'#111111'"'"' -bg '"'"'#111111'"'"
# ^^^^^ ^^^^^ ^^^^^ ^^^^
# 12345 12345 12345 1234


Explanation of how '"'"' is interpreted as just ':





  1. ' End first quotation which uses single quotes.

  2. " Start second quotation, using double-quotes.

  3. ' Quoted character.

  4. " End second quotation, using double-quotes.

  5. ' Start third quotation, using single quotes.



If you do not place any whitespaces between (1) and (2), or between (4) and (5), the shell will interpret that string as a one long word.



No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...