How do I do if statement arithmetic in bash?

This might work for you:

((a%4==0)) && echo "$a is divisible by 4" || echo "$a is not divisible by 4"

or more succinctly:

((a%4)) && echo "$a is not divisible by 4" || echo "$a is divisible by 4"

a=4
if [ $(( $a % 4 )) -eq 0 ]; then                                
     echo "I'm here"
fi

Single brackets ([..]) don't work for some tests. Try with double brackets ([[...]]) and enclose the mod in ((..)) to evaluate the % operator properly:

if [[ $(( $1 % 4 )) == 0 ]]; then

More details are in 7.2. More advanced if usage.


read n
if ! ((n % 4)); then
    echo "$n divisible by 4."
fi

The (( )) operator evaluates expressions as C arithmetic, and has a boolean return.

Hence, (( 0 )) is false, and (( 1 )) is true. [1]

The $(( )) operator also expands C arithmetic expressions, but instead of returning true/false, it returns the value instead. Because of this you can test the output if $(( )) in this fashion: [2]

[[ $(( n % 4 )) == 0 ]]

But this is tantamount to: if (function() == false). Thus the simpler and more idiomatic test is:

! (( n % 4 ))

[1]: Modern bash handles numbers up to your machine's intmax_t size.

[2]: Note that you can drop $ inside of (( )), because it dereferences variables within.

Tags:

Scripting

Bash