help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] best practice with handling syntax errors


From: Andy Chu
Subject: Re: [Help-bash] best practice with handling syntax errors
Date: Thu, 8 Dec 2016 09:35:04 -0800

On Thu, Dec 8, 2016 at 3:58 AM, Christof Warlich <address@hidden>
wrote:

> Hi,
>
>
> in our scripts, we usually set bash's -e option to ensure to fail as
> early as possible in case of errors. While this works rather well for
> most scenarios, it doesn't help in cases when either external or builtin
> commands with checked exit status are encountering syntax errors: In
> these cases, the script happily continues regardless of the presence of
> the -e option. This comes particularly to a surprise when testing
> conditions, e.g.:
>
> if [ -ee /etc/passwd ]; then
>
>     : # note the syntax error above
>
> fi
>

In the case of [, you can use [[ if you want better syntax errors.  Compare
the following:

$ if false; then [ -ee /etc/password ]; fi; echo $?
0

$ if false; then [[ -ee /etc/password ]]; fi; echo $?
-bash: conditional binary operator expected
-bash: syntax error near `/etc/password'

The "if false" shows that the error is detected at parse time, even if the
code is never run.  This is because [[ is NEITHER a external or builtin
command; it's part of the language proper.

In terms of bash's implementation, [[ is parsed in parse.y like like
for/if/while/function, whereas the builtins are in the builtins/ dir, and
only parsed during execution.  This fact isn't mentioned in "help [[" and I
discovered it while writing a bash parser, and I wrote about it here:

http://www.oilshell.org/blog/2016/10/12.html

This post goes into which shells parse more things up front, giving you
more parse errors:

http://www.oilshell.org/blog/2016/10/13.html

If you compare the constructs $() $(( )) and ${}, dash gives parse errors
for 2 out of 3, mksh gives parse errors for 1 out of 3, and bash and zsh
give errors for for 0 out of 3.  Parse errors meaning that you get them
without execution.

My oil shell parser gives errors for 3 out of 3, but I don't recommend you
actually use it yet since it's still a prototype.  The algorithm for
parsing is sound though, having been tested on a lot of real world scripts.

Andy


reply via email to

[Prev in Thread] Current Thread [Next in Thread]