Wednesday, January 18, 2012

Inserting single quote character inside a single-quoted string

“Strings” (not the same as strings in languages like C or Python) in shells (bash and zsh especially) can be enclosed within either single quotes (') or double quotes (").  Double quotes escape (i.e. remove special meaning from) characters like space and single quotes, but single quotes remove meaning from almost every special character including spaces, $, !, new lines, etc.  (Learn more)

You can use \ escape to insert a double quote character (") inside a double-quoted string, but you cannot do the same for inserting a single quote character (') inside a single-quoted string.  Because \ has no special meaning inside a single-quoted string.
% echo "abc \" def"
abc " def
% echo 'abc \' def'                   
quote> blah'
abc \ def
blah
%
But I often find myself needing to insert apostrophes inside single-quoted strings.  I use the following syntax then:
% echo 'There'\''s always a way out'
There's always a way out
Shells usually let you concatenate strings by just writing them together without any space between them: "abc""def" is the same as "abcdef" which is the same as "abc"'def' which is the same as abcdef (without quotes).  We use the same technique here: we have two different single-quoted strings: 'There' and 's always a way out'.  In between them we have a single-quote character escaped with \ to mean that we want a literal apostrophe character inserted.

No comments:

Post a Comment