bashexpr

Why does expr fail when matching a single 0


The following command works:

$ expr 1 : '\(.\)' || echo fail
1

When trying to match the string "0" the command fails, e.g. $? == 1:

$ expr 0 : '\(.\)' || echo fail
fail

The man page says:

Exit status is 0 if EXPRESSION is neither null nor 0

But, returning exit status 1 because the matching string is 0 does not make sense.


Solution

  • The exit status of expr depends on the string returned, not the operation that produces that string.

     The expr utility exits with one of the following values:
     0       the expression is neither an empty string nor 0.
     1       the expression is an empty string or 0.
     2       the expression is invalid.
    

    Since the returned string is 0, the exit status is 1.

    Whether you use a successful regular expression match or some other operator to produce the 0 isn't relevant.

    $ expr 3 - 3 || echo "fail"
    0
    fail