How to evaluate an arithmetic expression in an "if" statement?

This is my script:

#!/bin/bash
num=1
while [ $num -lt 100 ]
do
if [ $num % 3 -eq "0" ]
then
echo "fizz"
elif [ $num % 5 -eq "0" ]
then
echo "buzz"
elif [ $num % 3 -eq "0" ] && [ $num % 5 -eq "0" ]
then
echo "fizzbuzz"
else
echo $num
fi ((num++))
done

It keeps saying bash: [: too many arguments.

3

2 Answers

The correct syntax is:

if [ $(($num % 3)) -eq "0" ]

From man bash:

Arithmetic Expansion

Arithmetic expansion allows the evaluation of an arithmetic expression and the substitution of the result. The format for arithmetic expansion is: $((expression))

The expression $num % 3 must be evaluated before it can be compared using -eq.

0

To expand on Eric's answer, you actually can forgo the square brackets if you're simply testing equality with respect to 0. You can also omit the "$" as parameter dereferencing is optional. For the statement in his example,

if [ $(($num % 3)) -eq "0" ]

is equivalent to

if ! ((num % 3))

making sure to add in the "!" operator.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like