My question is why bash does not report against line 2 where I left off the trailing " at the end on purpose to see how it reports this back.
I run a bash script and get this error: ./test: line 4: unexpected EOF while looking for matching `"'
#!/usr/bin/bash
echo "this is life
echo "now is the time"
echo "have we reached the end"
Because that line doesn't contain an error, as it's perfectly legal to include a newline character in a quoted string.
As a matter of fact any character (but an unescaped
"
, which marks the start / end of a quoted string) could be included in a quoted string if somehow "put" after a"
character; a newline character just happens to be easily typed in (just like, e.g., any "ordinary" alphabetical character), and - notably - is not even the most exotic thing that you could include in a quoted string1.I suggest you break out of the mindset where a string can contain just letters, numbers and punctuation, as it's not like that at all, and being aware of this helps a lot in using the command line / scripting.
Anyways, more to the point, here's a breakdown of what happens and why you're being notified of an error only on line #4:
"
character; it starts intrepreting what follows after as a string, and when it stumbles upon the (as discussed above, legal) newline character, it happily swallows it and starts parsing line #3 as a continuation of the string that so far includes what followed the"
character, which includes the newline;"
character; the first string is now correctly and completely parsed. It then parses the remainder of the line as a (legal) unquoted string until the next"
character is found, when the cycle repeats: it stumbles upon the (again, as discussed above, legal) newline character, it happily swallows it and starts parsing line #4 as a continuation of the string that so far includes just the newline;"
character; the second string is now correctly and completely parsed. It then parses the remainder of the line as a (legal) unquoted string until the next"
character is found, when the cycle breaks; it stumbles upon the (again, as discussed above, legal) newline character, it happily swallows it and... there's nothing left to parse / EOF (End-Of-File) has been reached. Since EOF has been reached, the last parsed"
most definetly has no matching closing quote - hence the errorunexpected EOF while looking for matching `"'
is thrownIn fact, e.g., any other non-printable character (ASCII range 0-31 - and not just those) could also be included in a string if it was pasted after a `"` character. They're really no different from newlines - they're all non-printable characters - it just so happens that newlines can be simply typed in. Another exception to non-printable characters is the tab character, which, much like the newline character, also can be simply typed in.