9

I came across this question whose author had dealt with problem caused by: let x=1-1 exits with code 1.

According to bash manual:

If the last expression evaluates to 0, let returns 1; otherwise 0 is returned. (p. 56-57)

I'm not so familiar with bash nuances, so my question is "What is the reason of such behaviour?". May be that's because 0 interprets like 'false'? It's a bit strange for bash-beginner like me that 0 as a result of arithmetic expression leads to an error exit code...

1
  • 2
    There is one possible usage of this behaviour on my mind: exit status 1 means FALSE, so let ... can be used as logical expression for if, while etc. Am I right? Oct 4, 2021 at 17:09

1 Answer 1

14

A zero integer value evaluates to false when used in a boolean context in most general programming languages. This fact means you may have code like the following C code.

c = 100;
while (--c) { /* do something while c is non-zero */ }

In the shell, an exit status of one evaluates to false when used in a conditional context.

c=100
while let --c; do
    # do something while c is non-zero
done

Do you see the pattern here? The while loop runs until let returns a non-zero exit status, which it does when c reaches zero. The non-zero exit status does not mean "error" in this case, it only means let arrived at the result 0.

Usually, though, let is replaced with ((...)) (an arithmetic evaluation) nowadays, as in

c=100
while ((--c)); do ...; done

It's worth repeating that the while loops above do not care about c. They care about the exit status of the let built-in utility and of ((...)).

1
  • 2
    Note also how the 1 + 1 == 2 or 5 < 6 arithmetic expressions yield 1 and 6 < 5, 1 + 1 == 3 yield 0, as you can check with echo "$(( 1 + 1 == 2 ))" or (( a = 1 + 1 == 2 )); echo "$a $?" Oct 4, 2021 at 18:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .