help-bash
[Top][All Lists]
Advanced

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

[Help-bash] best practice with handling syntax errors


From: Christof Warlich
Subject: [Help-bash] best practice with handling syntax errors
Date: Thu, 8 Dec 2016 12:58:24 +0100
User-agent: Mozilla/5.0 (X11; Linux x86_64; rv:45.0) Gecko/20100101 Thunderbird/45.2.0

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

echo "script continues ..."

... which outputs:


line 2: [: -ee: unary operator expected
script continues ...

While I'm fully aware that the reported syntax error does not directly
come from the bash interpreter, but from the (builtin) test command,
which in turn just returns a non-zero exit status due to its misuse,
which is then being catched by the if-statement, this behaviour is rather
unexpected particularly for novice bash programmers.

My question: Are there any best practice recommondations w.r.t. how to
deal with situations like this? In the given example, the test builtin
command would return 0 without the syntax error and if /etc/passwd is
present, 1 if /etc/passwd in not present and 2 if the syntax error
occurs. But other programms that are typically used for testing
conditions (e.g. grep) may behave differently. Maybe there is a convention
that an expected exit status should always be 0 or 1, while anything
else is considered an unexpected error? If so, how to best discriminate
between expected and unexpected return codes, so that the latter cause
an immediate termination of scripts?

Thanks for any ideas on that topic,

Cheers,

Chris




reply via email to

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