I am just trying to get something straight as to why the following returns false:
echo $[ $(( 2100%4 )) == 0 ] --> returns '1'
I know I am probably missing something simple.
I am just trying to get something straight as to why the following returns false:
echo $[ $(( 2100%4 )) == 0 ] --> returns '1'
I know I am probably missing something simple.
In short "meaning" differs from "value".
A zero exit status means success. A nonzero exit status means failure.
A zero value is associated with "false" boolean state. A nonzero value is associated with "true" boolean state.
The [ ... ]
is the same as test ...
. The test
command exits with a nonzero exit status if the expression inside is false (as in really false, not true). The test
command exits with a zero exit status if the expression inside is true.
The $[ ... ]
is an old, undocumented and deprecated form of $(( ... ))
arithmetic expansion (there's also the expr ...
that you should not use).
The if expr; then body; fi
executes the body
part only if expr
exits with a zero exit status, ie. meaning "success" here.
So:
echo $[ $(( 2100%4 )) == 0 ]
will print 1
. The $(( 2100%4 ))
will do the arithmetic operation and expand to 0
. The arithmetic expansion work as in C language. The result of ==
arithmetic operation is 1
if the numbers are equal, it's 0
if the numbers are not equal. The $[ 0 == 0 ]
will do the arithmetic operation and expand to just a number 1
, as this will be the result of ==
operator.
While the:
[ $(( 2100%4 )) == 0 ]
Executes the [ 0 == 0 ]
, it's same as test 0 == 0
. Because the expression 0 == 0
evaluated by test
command is true, so test
command exits with 0
exit status, which means "success". Note that ==
is a bash extension for =
and it does string comparison, it compares 0
to 0
lexicographically. It does not compare numbers and it differs from arithmetic operator.
There is also bash extension (( ... ))
syntax. The (( ... ))
evaluates the arithmetic expression and if the result of arithmetic is equal to "true" boolean state (ie. it result in a nonzero value), then the (( .. ))
exits with a zero exit status (meaning success). If the expression evaluates to 0, ie. "false" boolean state, then the (( ... ))
exits with a nonzero exit status. Note the difference.
So you can:
if (( 2100%4 == 0 )); then something; fi
The 2100%4 == 0
is equal to 1
, which is "true" boolean state, which means ((
exits with a zero exit status, which means success, which means the body of the if
will execute.