Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does expr fail when matching a single 0

Tags:

bash

expr

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.

like image 553
Dag Lövenvald Avatar asked Apr 21 '26 15:04

Dag Lövenvald


1 Answers

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
like image 63
chepner Avatar answered Apr 23 '26 20:04

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!