Quote:
Originally Posted by cristalp
If so, the number of quote appearing in a code could only be even number, right?
|
No, this is not correct. However, there is in fact an error in my previous explanation (corrected it by now). The character that is responsible for the unclosed open quote is the last double-quote and not the last single-quote as initially stated. Single quotes do not get treated special inside double-quotes. Otherwise, as soon as bash encounters an opening single-quote, it will deactivate its escape mechanism. So let us review your initial example:
Code:
awk 'BEGIN {FS ="\'"}{print $2}'
^OQ -> deactivate escape mechanism
^ this backslash now loses its meaning as escape character
As you see, when the first opening quote (OQ) is encountered everything following it is passed as parameters to 'awk'. Even the backslash loses its meaning. Normally it would indicate that the character following it should not be interpreted as special. So the bold part is passed
as is to 'awk'.
Code:
awk 'BEGIN {FS ="\'"}{print $2}'
^CQ -> activate escape mechanism
^ this double quote now regains its special meaning
Now the quote following the backslash is interpreted as closing quote (CQ). At this point bash is capable of interpreting other special characters like " and \ again. So the " is interpreted as an opening double-quote that never gets closed.
Let us examine
Code:
awk 'BEGIN {FS ="'\''"}{print $2}'
^OQ ^CQ
^ the backslash now has special meaning
Here the bold part is passed
as is to awk because it is enclosed in single-quotes. As you see, the backslash now follows the closing quote. It is interpreted by bash as escape character because it is now
not part of an open quote. Therefore, the next (third) single-quote is being escaped and not interpreted as opening quote. The fourth single-quote then again opens it.
To sum it up:
Code:
$ echo single-quote \' # Just prepend a \
single-quote '
$ echo 'single-quote '\'' inside single-quotes' # Escape sequence: '\''
single-quote ' inside single-quotes
$ echo "single-quote ' inside double-quotes" # no need to escape it at all
single-quote ' inside double-quotes