Bash Script to Check Even or Odd Number
Use the Bash script with the modulo operator like
if (( number % 2 == 0 )); then echo \"Even\"; else echo \"Odd\"; fi to check if a number is even or odd.Examples
Input4
Output4 is Even
Input7
Output7 is Odd
Input0
Output0 is Even
How to Think About It
To check if a number is even or odd, divide it by 2 and look at the remainder. If the remainder is 0, the number is even; otherwise, it is odd.
Algorithm
1
Get the input number from the user.2
Calculate the remainder when the number is divided by 2.3
If the remainder is 0, print that the number is even.4
Otherwise, print that the number is odd.Code
bash
#!/bin/bash read -p "Enter a number: " number if (( number % 2 == 0 )); then echo "$number is Even" else echo "$number is Odd" fi
Output
Enter a number: 5
5 is Odd
Dry Run
Let's trace input 5 through the code
1
Input number
User enters 5, so number=5
2
Calculate remainder
5 % 2 = 1 (not zero)
3
Check remainder
Since remainder is 1, print '5 is Odd'
| Step | Operation | Value |
|---|---|---|
| 1 | Input number | 5 |
| 2 | 5 % 2 | 1 |
| 3 | Output | 5 is Odd |
Why This Works
Step 1: Using modulo operator
The % operator gives the remainder of division, which helps determine evenness.
Step 2: Condition check
If remainder is zero, the number divides evenly by 2, so it is even.
Step 3: Output result
Print a clear message stating if the number is even or odd.
Alternative Approaches
Using arithmetic expansion with if-else
bash
#!/bin/bash read -p "Enter a number: " n remainder=$(( n % 2 )) if [ $remainder -eq 0 ]; then echo "$n is Even" else echo "$n is Odd" fi
This uses classic test brackets and arithmetic expansion, which is more portable but slightly longer.
Using case statement
bash
#!/bin/bash read -p "Enter a number: " num case $((num % 2)) in 0) echo "$num is Even";; 1) echo "$num is Odd";; esac
Using case can be cleaner for multiple conditions but is less common for simple even/odd checks.
Complexity: O(1) time, O(1) space
Time Complexity
The modulo operation and condition check run in constant time regardless of input size.
Space Complexity
Only a few variables are used, so space usage is constant.
Which Approach is Fastest?
All approaches use simple arithmetic and condition checks, so they have similar performance; choice depends on readability and style.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Modulo with (( )) | O(1) | O(1) | Simple and modern Bash scripts |
| Modulo with [ ] test | O(1) | O(1) | More portable scripts |
| Case statement | O(1) | O(1) | When extending to multiple conditions |
Use
(( number % 2 == 0 )) for a concise and readable even/odd check in Bash.Forgetting to use double parentheses
(( )) for arithmetic evaluation causes syntax errors.