A low-tech approach is
tr -cd "'\n" < run_me.sh | awk 'length%2==1 {print NR, $0}'
The tr
deletes all characters except for single quotes and newlines,
and the awk
identifies the lines that have an odd numbers of characters
(i.e., non-matching quotes).
Check them out individually;
note that valid strings like "That's not a bug!"
will be flagged.
If this doesn’t highlight the problem, try again with tr -cd '"\n'
(to find non-matching double quotes).
Next, expand the tr
to allow ()
, []
, and ultimately {}
to go through. At this point,
manual inspection of the output becomes a less fruitful pursuit;
while (
and )
are usually matched within the same line,
and quotes and square brackets almost always are,
this is not true of {
and }
.
(However, looking for non-matching {
and }
would find the problem that the OP actually had, namely,
typing "${MY_ARRAY[@]"
instead of "${MY_ARRAY[@]}"
).
If you have narrowed the problem down to a curly brace mismatch,
and especially if you have narrowed down a range in the file, go to Plan B.
Open the file in vim
(or vi
).
Go to a {
character that you believe is before the error and type %
.
If the cursor jumps to the }
that you think matches the {
you started on,
move forward to the next {
and repeat.
If it jumps to a }
that doesn’t match the {
you started on,
the error occurs between those two braces.
If it doesn’t move,
the error occurs between your current location and the end of the file.
Zoom in.
This approach may be slightly better suited to program files
in languages like C, C++, and Java
(if their compilers don’t do a good enough job),
but it should work fairly well for shell scripts.
Best Answer
Bash built-ins are inconsistent and poorly documented.
Here's an example:
Even without
command
the return code$? -eq 0
and there is no error onstd err
.Another one:
All the arguments are optional but it returns
$? -eq 1
when there are none.I've even compiled the newest Bash 4.2 and here are my results:
There's a new section "Exit Status" and
command
is still an optional argument. Even worse than 3.x. The same for other built-ins.So, you're right. Bash built-ins are a mess and should be fixed.