Bash: How to Check if Number is Even or Odd


You can use the following syntax in Bash to check if a number is even or odd:

if [ $(( $num % 2)) -eq 0 ]
then
    echo "Number is even"
else
    echo "Number is odd"
fi

This particular example checks if the number stored in the variable named num is even or odd and outputs one of the following strings as a result:

  • “Number is even”
  • “Number is odd”

Note that we use the logic $(( $num % 2)) -eq 0 to check if the number divided by 2 produces a remainder equal to zero.

If the remainder produced is equal to zero then the number is even.

Otherwise, the number is odd.

The following example shows how to use this syntax in practice.

Example: How to Check if Number is Even or Odd in Bash

Suppose we have a variable named num with a value of 17 in Bash.

We can use the following syntax to check if this number is even or odd:

num=17

if [ $(( $num % 2)) -eq 0 ]
then
    echo "Number is even"
else
    echo "Number is odd"
fi

The following screenshot shows how to use this syntax in practice:

Bash check if number is even or odd

This returns “Number is odd” since the variable named num contains the value 17, which is odd.

Suppose instead that our variable named num has a value of 16.

We can use the following syntax to check if this number is even or odd:

num=16

if [ $(( $num % 2)) -eq 0 ]
then
    echo "Number is even"
else
    echo "Number is odd"
fi

The following screenshot shows how to use this syntax in practice:

Bash if else statement to check if number is even or odd

This returns “Number is even” since the variable named num contains the value 16, which is even.

Note: Feel free to return any text you’d like as output in the if else statement.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

Bash: How to Generate a Sequence of Numbers
Bash: How to Check if Number is Within a Range
Bash: How to Round Numbers to 2 Decimal Places
Bash: How to Count Number of Blank Lines in File

Leave a Reply